How projectdiscovery/goflags works
Project Type and Purpose
• Project Type: An open‑source Go library extending the standard flag package.
• Purpose: Provide convenience functions, custom flag types (slices, maps, enums, callbacks), YAML config support, grouped flags, and improved usage output.
File Structure
• Root files: various *_var.go files implement each custom flag type (e.g., string_slice.go, enum_var.go, callback_var.go).
• goflags.go: central entrypoint defining NewFlagSet, core structs, and high‑level methods (Parse, MergeConfigFile, CreateGroup).
• examples/: a sample client demonstrating typical integration flow.
• Tests in each *_test.go validate type behavior.
• ports_data.json: static data used by PortVar.
• No external services, no frontend/backend split.
Core Components
• Imports github.com/projectdiscovery/goflags
• Calls NewFlagSet()
• Registers flags (BoolVar, StringSliceVarP, EnumVarP, CallbackVar, etc.)
• Optionally calls MergeConfigFile()
• Calls Parse()
A. FlagSet Manager
– Backed by Go’s flag.FlagSet
– Methods: NewFlagSet(), Parse(), MergeConfigFile(), CreateGroup(), SetDescription()
B. Config Loader
– YAML reading & merging into existing flags
C. Custom Variable Types
– StringSlice types (comma‑sep, normalized, file‑based)
– RuntimeMap (map[string]string)
– Enum types
– CallbackVar
– PortVar (uses ports_data.json)
– SizeVar, DurationVar, BoolVar, IntVar
D. Usage Template
– Improves on standard usage text (leverages spf13/cobra templates)
• Standard Library Dependency
– flag package
• External Assets
– ports_data.json
– (Optional) github.com/spf13/cobra for templates
Relationships and Interactions
• The Client calls into the FlagSet Manager to register flags.
• Each registration ties a variable pointer to a custom Var implementation.
• On Parse(), FlagSet iterates registered flags, invoking the underlying flag parse logic.
• If a config file is provided, the Config Loader reads YAML, maps keys to flags, and re‐invokes each Var’s Set() method.
• After parsing, the client reads the populated variables.
Architectural Patterns and Design Principles
• Dependency Injection: client provides pointers to its own variables.
• Strategy Pattern: each custom Var type implements the flag.Value interface.
• Single Responsibility: separate files and types for each Var; one module for config merging.
• Extensibility: new Var types can be added by implementing flag.Value.