Documentation
¶
Overview ¶
Package flag implements command-line flag parsing.
Usage:
Define flags using flag.String(), Bool(), Int(), etc.
This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
import "flag"
var ip = flag.Int("flagname", 1234, "help message for flagname")
If you like, you can bind the flag to a variable using the Var() functions.
var flagvar int
func init() {
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}
Or you can create custom flags that satisfy the Value interface (with pointer receivers) and couple them to flag parsing by
flag.Var(&flagVal, "name", "help message for flagname")
For such flags, the default value is just the initial value of the variable.
After all flags are defined, call
flag.Parse()
to parse the command line into the defined flags.
Flags may then be used directly. If you're using the flags themselves, they are all pointers; if you bind to variables, they're values.
fmt.Println("ip has value ", *ip)
fmt.Println("flagvar has value ", flagvar)
After parsing, the arguments following the flags are available as the slice flag.Args() or individually as flag.Arg(i). The arguments are indexed from 0 through flag.NArg()-1.
Command line flag syntax:
-flag -flag=x -flag x // non-boolean flags only
One or two minus signs may be used; they are equivalent. The last form is not permitted for boolean flags because the meaning of the command
cmd -x *
will change if there is a file called 0, false, etc. You must use the -flag=false form to turn off a boolean flag.
Flag parsing stops just before the first non-flag argument ("-" is a non-flag argument) or after the terminator "--".
Integer flags accept 1234, 0664, 0x1234 and may be negative. Boolean flags may be:
1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False
Duration flags accept any input valid for time.ParseDuration.
The default set of command-line flags is controlled by top-level functions. The FlagSet type allows one to define independent sets of flags, such as to implement subcommands in a command-line interface. The methods of FlagSet are analogous to the top-level functions for the command-line flag set.
Example ¶
package main
import ()
func main() {
// All the interesting pieces are with the variables declared above, but
// to enable the flag package to see the flags defined there, one must
// execute, typically at the start of main (not init!):
// flag.Parse()
// We don't run it here because this is not a main function and
// the testing suite has already parsed the flags.
}
Output:
Example (ArgsEnvFilePrecedence) ¶
Example_argsEnvFilePrecedence shows how command line overrides env which overrides file which overrides default.
package main
import (
"fmt"
"os"
"path/filepath"
lib "github.com/machship/flag"
)
func main() {
lib.ResetForTesting(nil)
// Register flags & config file flag.
lib.String(lib.DefaultConfigFlagname, "", "config file")
host := lib.String("host", "default-host", "service host")
port := lib.Int("port", 8080, "service port")
// Create config file with baseline values.
cfg := filepath.Join(os.TempDir(), "precedence.conf")
os.WriteFile(cfg, []byte("host file-host\nport 9000\n"), 0o600)
defer os.Remove(cfg)
// Set env vars (will override file if no CLI override)
os.Setenv("HOST", "env-host")
os.Setenv("PORT", "9100")
defer os.Unsetenv("HOST")
defer os.Unsetenv("PORT")
// Provide CLI args overriding only host (not port) and supply config file.
os.Args = []string{"app", "-config", cfg, "-host", "cli-host"}
lib.Parse()
fmt.Printf("host=%s port=%d\n", *host, *port) // host from CLI, port from env
}
Output: host=cli-host port=9100
Example (Basic) ¶
Example_basic shows the simplest use: define a flag and parse args.
package main
import (
"fmt"
"os"
lib "github.com/machship/flag"
)
func main() {
lib.ResetForTesting(nil) // ensure a clean CommandLine
age := lib.Int("age", 0, "age of gopher")
// Simulate command-line: program name + flags
os.Args = []string{"cmd", "-age", "7"}
lib.Parse()
fmt.Println("age:", *age)
}
Output: age: 7
Example (ConfigFile) ¶
Example_configFile shows using the built-in config file flag (default name "config").
package main
import (
"fmt"
"os"
"path/filepath"
lib "github.com/machship/flag"
)
func main() {
lib.ResetForTesting(nil)
name := lib.String("name", "", "user name")
// Register the config flag so the library knows where to load from.
lib.String(lib.DefaultConfigFlagname, "", "config file path")
// Create a temporary config file.
tmpDir := os.TempDir()
cfgPath := filepath.Join(tmpDir, "example_flag.conf")
// File supports either "key value" or "key=value" forms.
os.WriteFile(cfgPath, []byte("name Alice\n"), 0o600)
defer os.Remove(cfgPath)
// Provide -config argument pointing to the file.
os.Args = []string{"app", "-config", cfgPath}
lib.Parse()
fmt.Println("name:", *name)
}
Output: name: Alice
Example (CustomFlagSetWithPrefix) ¶
Example_customFlagSetWithPrefix shows using a separate FlagSet with an environment variable prefix.
package main
import (
"fmt"
"os"
lib "github.com/machship/flag"
)
func main() {
fs := lib.NewFlagSetWithEnvPrefix("service", "APP", lib.ContinueOnError)
p := fs.Int("port", 0, "service port")
os.Setenv("APP_PORT", "7777")
defer os.Unsetenv("APP_PORT")
// No CLI args, Parse() pulls from env.
if err := fs.Parse([]string{}); err != nil {
panic(err)
}
fmt.Println("port:", *p)
}
Output: port: 7777
Example (EnumAndCollections) ¶
Example_enumAndCollections demonstrates enum, duration slice, and string map flags.
package main
import (
"fmt"
"os"
"time"
lib "github.com/machship/flag"
)
func main() {
lib.ResetForTesting(nil)
color := lib.Enum("color", "red", []string{"red", "green", "blue"}, "color choice")
intervals := lib.DurationSlice("intervals", ",", []time.Duration{}, "comma separated durations")
labels := lib.StringMap("labels", map[string]string{}, "key=value pairs")
os.Args = []string{"cmd", "-color", "green", "-intervals", "1s,2s,500ms", "-labels", "env=prod,ver=1"}
lib.Parse()
fmt.Println("color:", *color)
fmt.Println("interval count:", len(*intervals))
fmt.Println("labels ver:", (*labels)["ver"])
}
Output: color: green interval count: 3 labels ver: 1
Example (Environment) ¶
Example_environment demonstrates reading a value from the environment when it is not supplied on the command line.
package main
import (
"fmt"
"os"
lib "github.com/machship/flag"
)
func main() {
lib.ResetForTesting(nil)
// Define the flag.
port := lib.Int("port", 8080, "service port")
// Set environment variable PORT (uppercase name of flag)
os.Setenv("PORT", "9000")
defer os.Unsetenv("PORT")
os.Args = []string{"svc"} // no -port argument provided
lib.Parse()
fmt.Println("port:", *port)
}
Output: port: 9000
Example (ExtendedTypes) ¶
Example_extendedTypes shows some additional custom types supported (ByteSize and time with layout).
package main
import (
"fmt"
"os"
"time"
lib "github.com/machship/flag"
)
func main() {
lib.ResetForTesting(nil)
size := lib.ByteSizeFlag("size", 0, "buffer size")
ts := lib.Time("start", time.RFC3339, time.Time{}, "start time (RFC3339)")
os.Args = []string{"cmd", "-size", "10KiB", "-start", "2023-01-02T03:04:05Z"}
lib.Parse()
fmt.Println("size:", *size) // prints raw bytes value
fmt.Println("start year:", ts.Year())
}
Output: size: 10240 start year: 2023
Example (Extended_types) ¶
Example_extended_types covers many custom Value types provided by the library.
package main
import (
"encoding/json"
"fmt"
"net"
neturl "net/url"
"os"
"time"
"github.com/google/uuid"
lib "github.com/machship/flag"
decimal "github.com/shopspring/decimal"
)
func main() {
lib.ResetForTesting(nil)
dec := decimal.NewFromFloat(0)
lib.DecimalVar(&dec, "price", decimal.NewFromFloat(0), "decimal price")
var when time.Time
lib.TimeVar(&when, "when", time.RFC3339, time.Time{}, "timestamp")
var ip net.IP
lib.IPVar(&ip, "ip", nil, "ip address")
var ipn net.IPNet
lib.IPNetVar(&ipn, "cidr", nil, "network cidr")
var u neturl.URL
lib.URLVar(&u, "url", nil, "resource URL")
var id uuid.UUID
lib.UUIDVar(&id, "id", uuid.UUID{}, "identifier")
bs := lib.ByteSizeFlag("mem", 0, "memory size")
ss := lib.StringSlice("tags", ",", []string{}, "comma tags")
ds := lib.DurationSlice("intervals", ",", []time.Duration{}, "durations")
mp := lib.StringMap("labels", map[string]string{}, "k=v pairs")
var raw json.RawMessage
lib.JSONVar(&raw, "json", nil, "json blob")
enum := lib.Enum("env", "dev", []string{"dev", "prod"}, "environment")
os.Args = []string{"cmd",
"-price", "12.34", "-when", "2023-01-02T03:04:05Z",
"-ip", "127.0.0.1", "-cidr", "10.0.0.0/8", "-url", "https://example.com/x",
"-id", "123e4567-e89b-12d3-a456-426614174000", "-mem", "5MiB",
"-tags", "a,b", "-intervals", "1s,2s", "-labels", "k1=v1,k2=v2",
"-json", "{\"k\":1}", "-env", "prod",
}
lib.Parse()
fmt.Println("env:", *enum, "mem:", *bs, "tags:", len(*ss), "intervals:", len(*ds), "labels:", len(*mp))
}
Output: env: prod mem: 5242880 tags: 2 intervals: 2 labels: 2
Example (StructParsing) ¶
Example_structParsing shows defining flags from a struct using tags.
package main
import (
"fmt"
"os"
"time"
lib "github.com/machship/flag"
)
func main() {
lib.ResetForTesting(nil)
type Config struct {
Host string `flag:"host" default:"localhost" help:"service host"`
Port int `flag:"port" default:"8080" help:"service port"`
Debug bool `flag:"debug" required:"true" help:"enable debug"`
Delay time.Duration `flag:"delay" default:"250ms"`
}
var cfg Config
os.Args = []string{"svc", "-debug", "-port", "9001"}
if err := lib.ParseStruct(&cfg); err != nil {
panic(err)
}
fmt.Printf("%s:%d debug=%v delay=%s\n", cfg.Host, cfg.Port, cfg.Debug, cfg.Delay)
}
Output: localhost:9001 debug=true delay=250ms
Example (Struct_basic) ¶
Example_struct_basic shows using ParseStruct with defaults and a required flag.
package main
import (
"fmt"
"os"
"time"
lib "github.com/machship/flag"
)
func main() {
lib.ResetForTesting(nil)
type Config struct {
Endpoint string `flag:"endpoint" default:"https://api.example" help:"API base URL"`
Timeout time.Duration `flag:"timeout" default:"2s" help:"request timeout"`
Debug bool `flag:"debug" required:"true" help:"enable debug logging"`
}
var cfg Config
os.Args = []string{"svc", "-debug"}
if err := lib.ParseStruct(&cfg); err != nil {
panic(err)
}
fmt.Printf("endpoint=%s timeout=%s debug=%v\n", cfg.Endpoint, cfg.Timeout, cfg.Debug)
}
Output: endpoint=https://api.example timeout=2s debug=true
Example (Struct_byteSizeAndMap) ¶
Example_struct_byteSizeAndMap defaults & required interplay.
package main
import (
"fmt"
"os"
lib "github.com/machship/flag"
)
func main() {
lib.ResetForTesting(nil)
type Opts struct {
Cache lib.ByteSize `flag:"cache" default:"256KiB"`
Meta map[string]string `flag:"meta" default:"a=1,b=2"`
}
var o Opts
os.Args = []string{"tool"}
if err := lib.ParseStruct(&o); err != nil {
panic(err)
}
fmt.Printf("cache=%d meta=%d\n", o.Cache, len(o.Meta))
}
Output: cache=262144 meta=2
Example (Struct_enumsAndNumerics) ¶
Example_struct_enumsAndNumerics demonstrates enum validation & numeric parsing via struct tags.
package main
import (
"fmt"
"os"
lib "github.com/machship/flag"
)
func main() {
lib.ResetForTesting(nil)
type Limits struct {
Mode string `flag:"mode" enum:"fast,slow" default:"fast"`
Retries int `flag:"retries" default:"3"`
Rate float64 `flag:"rate" default:"1.5"`
}
var lim Limits
os.Args = []string{"app", "-mode", "slow", "-retries", "5"}
if err := lib.ParseStruct(&lim); err != nil {
panic(err)
}
fmt.Printf("mode=%s retries=%d rate=%.1f\n", lim.Mode, lim.Retries, lim.Rate)
}
Output: mode=slow retries=5 rate=1.5
Example (Struct_error) ¶
Example_struct_error demonstrates capturing an invalid default error for teaching purposes. (We run it as an example but only assert the prefix to keep it stable.)
package main
import (
"fmt"
"os"
"strings"
lib "github.com/machship/flag"
)
func main() {
lib.ResetForTesting(nil)
type Bad struct {
N int `flag:"n" default:"NaN"`
}
var b Bad
os.Args = []string{"bad"}
err := lib.ParseStruct(&b)
if err != nil && strings.Contains(err.Error(), "invalid default int") {
fmt.Println("error: invalid default int")
}
}
Output: error: invalid default int
Example (VarRegistration) ¶
Example_varRegistration shows manual Var usage for a big.Int.
package main
import (
"fmt"
"math/big"
"os"
lib "github.com/machship/flag"
)
func main() {
lib.ResetForTesting(nil)
bi := new(big.Int)
lib.BigIntVar(bi, "big", nil, "big integer value")
os.Args = []string{"app", "-big", "0x10"}
lib.Parse()
fmt.Println("big:", bi.String())
}
Output: big: 16
Example (ZeroValuesAndPrintDefaults) ¶
Example_zeroValuesAndPrintDefaults illustrates PrintDefaults output (truncated by checking substring).
package main
import (
lib "github.com/machship/flag"
)
func main() {
lib.ResetForTesting(nil)
// Redirect output to buffer (use bytes in real code; here just call directly for demonstration)
lib.String("name", "", "user name")
// We won't assert output to avoid brittleness; example just ensures no panic.
// No Output section means test harness only verifies it runs.
}
Output:
Index ¶
- Variables
- func Arg(i int) string
- func Args() []string
- func BigInt(name string, value *big.Int, usage string) *big.Int
- func BigIntVar(p *big.Int, name string, value *big.Int, usage string)
- func BigRat(name string, value *big.Rat, usage string) *big.Rat
- func BigRatVar(p *big.Rat, name string, value *big.Rat, usage string)
- func Bool(name string, value bool, usage string) *bool
- func BoolVar(p *bool, name string, value bool, usage string)
- func ByteSizeVar(p *ByteSize, name string, value ByteSize, usage string)
- func Decimal(name string, value decimal.Decimal, usage string) *decimal.Decimal
- func DecimalVar(p *decimal.Decimal, name string, value decimal.Decimal, usage string)
- func Deferred(fn func() error)
- func Deprecate(name, replacement string)
- func Duration(name string, value time.Duration, usage string) *time.Duration
- func DurationSlice(name, sep string, value []time.Duration, usage string) *[]time.Duration
- func DurationSliceVar(p *[]time.Duration, name, sep string, value []time.Duration, usage string)
- func DurationVar(p *time.Duration, name string, value time.Duration, usage string)
- func Enum(name string, value string, allowed []string, usage string) *string
- func EnumVar(p *string, name string, value string, allowed []string, usage string)
- func Float64(name string, value float64, usage string) *float64
- func Float64Var(p *float64, name string, value float64, usage string)
- func IP(name string, value net.IP, usage string) *net.IP
- func IPNet(name string, value *net.IPNet, usage string) *net.IPNet
- func IPNetVar(p *net.IPNet, name string, value *net.IPNet, usage string)
- func IPVar(p *net.IP, name string, value net.IP, usage string)
- func Int(name string, value int, usage string) *int
- func Int64(name string, value int64, usage string) *int64
- func Int64Var(p *int64, name string, value int64, usage string)
- func IntVar(p *int, name string, value int, usage string)
- func JSON(name string, value json.RawMessage, usage string) *json.RawMessage
- func JSONVar(p *json.RawMessage, name string, value json.RawMessage, usage string)
- func NArg() int
- func NFlag() int
- func OnChange(name string, fn func(string))
- func Parse()
- func ParseStruct(s any) error
- func ParseStructWithOptions(s any, opts ParseStructOptions) error
- func Parsed() bool
- func PrintDefaults()
- func Regexp(name string, value *regexp.Regexp, usage string) **regexp.Regexp
- func RegexpVar(p **regexp.Regexp, name string, value *regexp.Regexp, usage string)
- func RegisterStructHandler(t reflect.Type, h FieldHandler)
- func Set(name, value string) error
- func StartWatcher(secretDir, configFile string) error
- func StopWatcher() error
- func String(name string, value string, usage string) *string
- func StringMap(name string, value map[string]string, usage string) *map[string]string
- func StringMapVar(p *map[string]string, name string, value map[string]string, usage string)
- func StringSlice(name, sep string, value []string, usage string) *[]string
- func StringSliceVar(p *[]string, name, sep string, value []string, usage string)
- func StringVar(p *string, name string, value string, usage string)
- func Time(name, layout string, value time.Time, usage string) *time.Time
- func TimeSlice(name, sep, layout string, value []time.Time, usage string) *[]time.Time
- func TimeSliceVar(p *[]time.Time, name, sep, layout string, value []time.Time, usage string)
- func TimeVar(p *time.Time, name, layout string, value time.Time, usage string)
- func URL(name string, value *neturl.URL, usage string) *neturl.URL
- func URLVar(p *neturl.URL, name string, value *neturl.URL, usage string)
- func UUID(name string, value uuid.UUID, usage string) *uuid.UUID
- func UUIDVar(p *uuid.UUID, name string, value uuid.UUID, usage string)
- func Uint(name string, value uint, usage string) *uint
- func Uint64(name string, value uint64, usage string) *uint64
- func Uint64Var(p *uint64, name string, value uint64, usage string)
- func UintVar(p *uint, name string, value uint, usage string)
- func UnquoteUsage(flag *Flag) (name string, usage string)
- func Validate() error
- func Var(value Value, name string, usage string)
- func Visit(fn func(*Flag))
- func VisitAll(fn func(*Flag))
- func WithArgs(args []string, fn func() error) error
- type ByteSize
- type ErrorHandling
- type FieldHandler
- type Flag
- type FlagMeta
- type FlagSet
- func (f *FlagSet) Arg(i int) string
- func (f *FlagSet) Args() []string
- func (f *FlagSet) BigInt(name string, value *big.Int, usage string) *big.Int
- func (f *FlagSet) BigIntVar(p *big.Int, name string, value *big.Int, usage string)
- func (f *FlagSet) BigRat(name string, value *big.Rat, usage string) *big.Rat
- func (f *FlagSet) BigRatVar(p *big.Rat, name string, value *big.Rat, usage string)
- func (f *FlagSet) Bool(name string, value bool, usage string) *bool
- func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string)
- func (f *FlagSet) ByteSizeFlag(name string, value ByteSize, usage string) *ByteSize
- func (f *FlagSet) ByteSizeVar(p *ByteSize, name string, value ByteSize, usage string)
- func (f *FlagSet) Decimal(name string, value decimal.Decimal, usage string) *decimal.Decimal
- func (f *FlagSet) DecimalVar(p *decimal.Decimal, name string, value decimal.Decimal, usage string)
- func (f *FlagSet) Deferred(fn func() error)
- func (f *FlagSet) Deprecate(name, replacement string)
- func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration
- func (f *FlagSet) DurationSlice(name, sep string, value []time.Duration, usage string) *[]time.Duration
- func (f *FlagSet) DurationSliceVar(p *[]time.Duration, name, sep string, value []time.Duration, usage string)
- func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string)
- func (f *FlagSet) Enum(name string, value string, allowed []string, usage string) *string
- func (f *FlagSet) EnumVar(p *string, name string, value string, allowed []string, usage string)
- func (f *FlagSet) Float64(name string, value float64, usage string) *float64
- func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string)
- func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP
- func (f *FlagSet) IPNet(name string, value *net.IPNet, usage string) *net.IPNet
- func (f *FlagSet) IPNetVar(p *net.IPNet, name string, value *net.IPNet, usage string)
- func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string)
- func (f *FlagSet) Init(name string, errorHandling ErrorHandling)
- func (f *FlagSet) Int(name string, value int, usage string) *int
- func (f *FlagSet) Int64(name string, value int64, usage string) *int64
- func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string)
- func (f *FlagSet) IntVar(p *int, name string, value int, usage string)
- func (f *FlagSet) Introspect() []FlagMeta
- func (f *FlagSet) JSON(name string, value json.RawMessage, usage string) *json.RawMessage
- func (f *FlagSet) JSONVar(p *json.RawMessage, name string, value json.RawMessage, usage string)
- func (f *FlagSet) Lookup(name string) *Flag
- func (f *FlagSet) MarkSensitive(names ...string)
- func (f *FlagSet) NArg() int
- func (f *FlagSet) NFlag() int
- func (f *FlagSet) OnChange(name string, fn func(string))
- func (f *FlagSet) Parse(arguments []string) error
- func (f *FlagSet) ParseEnv(environ []string) error
- func (f *FlagSet) ParseFile(path string) error
- func (f *FlagSet) ParseSecretDir(dir string) error
- func (f *FlagSet) Parsed() bool
- func (f *FlagSet) PrintDefaults()
- func (f *FlagSet) Regexp(name string, value *regexp.Regexp, usage string) **regexp.Regexp
- func (f *FlagSet) RegexpVar(p **regexp.Regexp, name string, value *regexp.Regexp, usage string)
- func (f *FlagSet) Set(name, value string) error
- func (f *FlagSet) SetOutput(output io.Writer)
- func (f *FlagSet) StartWatcher(secretDir, configFile string) error
- func (f *FlagSet) StopWatcher() error
- func (f *FlagSet) String(name string, value string, usage string) *string
- func (f *FlagSet) StringMap(name string, value map[string]string, usage string) *map[string]string
- func (f *FlagSet) StringMapVar(p *map[string]string, name string, value map[string]string, usage string)
- func (f *FlagSet) StringSlice(name, sep string, value []string, usage string) *[]string
- func (f *FlagSet) StringSliceVar(p *[]string, name, sep string, value []string, usage string)
- func (f *FlagSet) StringVar(p *string, name string, value string, usage string)
- func (f *FlagSet) Time(name, layout string, value time.Time, usage string) *time.Time
- func (f *FlagSet) TimeSlice(name, sep, layout string, value []time.Time, usage string) *[]time.Time
- func (f *FlagSet) TimeSliceVar(p *[]time.Time, name, sep, layout string, value []time.Time, usage string)
- func (f *FlagSet) TimeVar(p *time.Time, name, layout string, value time.Time, usage string)
- func (f *FlagSet) URL(name string, value *neturl.URL, usage string) *neturl.URL
- func (f *FlagSet) URLVar(p *neturl.URL, name string, value *neturl.URL, usage string)
- func (f *FlagSet) UUID(name string, value uuid.UUID, usage string) *uuid.UUID
- func (f *FlagSet) UUIDVar(p *uuid.UUID, name string, value uuid.UUID, usage string)
- func (f *FlagSet) Uint(name string, value uint, usage string) *uint
- func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64
- func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string)
- func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string)
- func (f *FlagSet) Validate() error
- func (f *FlagSet) Var(value Value, name string, usage string)
- func (f *FlagSet) Visit(fn func(*Flag))
- func (f *FlagSet) VisitAll(fn func(*Flag))
- type Getter
- type MultiError
- type ParseStructOptions
- type StructFieldContext
- type Value
Examples ¶
- Package
- Package (ArgsEnvFilePrecedence)
- Package (Basic)
- Package (ConfigFile)
- Package (CustomFlagSetWithPrefix)
- Package (EnumAndCollections)
- Package (Environment)
- Package (ExtendedTypes)
- Package (Extended_types)
- Package (StructParsing)
- Package (Struct_basic)
- Package (Struct_byteSizeAndMap)
- Package (Struct_enumsAndNumerics)
- Package (Struct_error)
- Package (VarRegistration)
- Package (ZeroValuesAndPrintDefaults)
Constants ¶
This section is empty.
Variables ¶
var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
CommandLine is the default set of command-line flags, parsed from os.Args. The top-level functions such as BoolVar, Arg, and so on are wrappers for the methods of CommandLine.
var DefaultConfigFlagname = "config"
DefaultConfigFlagname defines the flag name of the optional config file path. Used to lookup and parse the config file when a default is set and available on disk.
var DefaultSecretDirFlagname = "secret-dir"
DefaultSecretDirFlagname defines an optional flag name whose value, if set, points to a directory containing secret files (each filename = flag name or underscore variant). If present, it is processed after environment variables and before the config file.
var EnvironmentPrefix = ""
EnvironmentPrefix defines a string that will be implicitely prefixed to a flag name before looking it up in the environment variables.
var ErrHelp = errors.New("flag: help requested")
ErrHelp is the error returned if the -help or -h flag is invoked but no such flag is defined.
var Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) PrintDefaults() }
Usage prints to standard error a usage message documenting all defined command-line flags. It is called when an error occurs while parsing flags. The function is a variable that may be changed to point to a custom function. By default it prints a simple header and calls PrintDefaults; for details about the format of the output and how to control it, see the documentation for PrintDefaults.
Functions ¶
func Arg ¶
Arg returns the i'th command-line argument. Arg(0) is the first remaining argument after flags have been processed. Arg returns an empty string if the requested element does not exist.
func Bool ¶
Bool defines a bool flag with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the flag.
func BoolVar ¶
BoolVar defines a bool flag with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the flag.
func ByteSizeVar ¶ added in v0.250905.1
func DecimalVar ¶ added in v0.250905.1
func Deferred ¶ added in v0.250905.1
func Deferred(fn func() error)
Deferred adds a function to the default CommandLine FlagSet's deferred validations.
func Deprecate ¶ added in v0.250905.1
func Deprecate(name, replacement string)
Deprecate global helper for default CommandLine set.
func Duration ¶
Duration defines a time.Duration flag with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the flag. The flag accepts a value acceptable to time.ParseDuration.
func DurationSlice ¶ added in v0.250905.1
func DurationSliceVar ¶ added in v0.250905.1
func DurationVar ¶
DurationVar defines a time.Duration flag with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the flag. The flag accepts a value acceptable to time.ParseDuration.
func Float64 ¶
Float64 defines a float64 flag with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the flag.
func Float64Var ¶
Float64Var defines a float64 flag with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the flag.
func Int ¶
Int defines an int flag with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the flag.
func Int64 ¶
Int64 defines an int64 flag with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the flag.
func Int64Var ¶
Int64Var defines an int64 flag with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the flag.
func IntVar ¶
IntVar defines an int flag with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the flag.
func JSON ¶ added in v0.250905.1
func JSON(name string, value json.RawMessage, usage string) *json.RawMessage
func JSONVar ¶ added in v0.250905.1
func JSONVar(p *json.RawMessage, name string, value json.RawMessage, usage string)
func NArg ¶
func NArg() int
NArg is the number of arguments remaining after flags have been processed.
func Parse ¶
func Parse()
Parse parses the command-line flags from os.Args[1:]. Must be called after all flags are defined and before flags are accessed by the program.
func ParseStruct ¶ added in v0.250905.1
ParseStruct preserves legacy behavior (auto parse).
func ParseStructWithOptions ¶ added in v0.250905.1
func ParseStructWithOptions(s any, opts ParseStructOptions) error
ParseStructWithOptions allows disabling automatic final Parse().
func PrintDefaults ¶
func PrintDefaults()
PrintDefaults prints, to standard error unless configured otherwise, a usage message showing the default settings of all defined command-line flags. For an integer valued flag x, the default output has the form
-x int usage-message-for-x (default 7)
The usage message will appear on a separate line for anything but a bool flag with a one-byte name. For bool flags, the type is omitted and if the flag name is one byte the usage message appears on the same line. The parenthetical default is omitted if the default is the zero value for the type. The listed type, here int, can be changed by placing a back-quoted name in the flag's usage string; the first such item in the message is taken to be a parameter name to show in the message and the back quotes are stripped from the message when displayed. For instance, given
flag.String("I", "", "search `directory` for include files")
the output will be
-I directory search directory for include files.
func RegisterStructHandler ¶ added in v0.250905.1
func RegisterStructHandler(t reflect.Type, h FieldHandler)
RegisterStructHandler allows users to plug in custom struct field handling for ParseStruct. The handler is invoked before built-in logic. If it returns (handled=true) no further processing occurs for that field.
Typical usage (example: base64-decoded string field):
type B64String string
func init() {
flag.RegisterStructHandler(reflect.TypeOf(B64String("")), func(ctx *flag.StructFieldContext) (bool, error) {
def := string(ctx.Value.String())
if ctx.DefaultTag != "" { def = ctx.DefaultTag }
// store raw default first
if err := flag.CommandLine.Set(ctx.FlagName, def); err != nil { return true, err }
// but ParseStruct registers via XXXVar helpers; emulate:
p := (*string)(ctx.Value.Addr().Interface().(*B64String))
flag.StringVar(p, ctx.FlagName, def, ctx.Help)
return true, nil
})
}
Handlers run before legacy switch/case fallback. If multiple handlers are registered for the same concrete type, the last wins.
func StartWatcher ¶ added in v0.250905.1
StartWatcher enables watching on default CommandLine FlagSet.
func StopWatcher ¶ added in v0.250905.1
func StopWatcher() error
StopWatcher stops watching on default CommandLine FlagSet.
func String ¶
String defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.
func StringMapVar ¶ added in v0.250905.1
func StringSlice ¶ added in v0.250905.1
func StringSliceVar ¶ added in v0.250905.1
func StringVar ¶
StringVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.
func TimeSliceVar ¶ added in v0.250905.1
func Uint ¶
Uint defines a uint flag with specified name, default value, and usage string. The return value is the address of a uint variable that stores the value of the flag.
func Uint64 ¶
Uint64 defines a uint64 flag with specified name, default value, and usage string. The return value is the address of a uint64 variable that stores the value of the flag.
func Uint64Var ¶
Uint64Var defines a uint64 flag with specified name, default value, and usage string. The argument p points to a uint64 variable in which to store the value of the flag.
func UintVar ¶
UintVar defines a uint flag with specified name, default value, and usage string. The argument p points to a uint variable in which to store the value of the flag.
func UnquoteUsage ¶
UnquoteUsage extracts a back-quoted name from the usage string for a flag and returns it and the un-quoted usage. Given "a `name` to show" it returns ("name", "a name to show"). If there are no back quotes, the name is an educated guess of the type of the flag's value, or the empty string if the flag is boolean.
func Validate ¶ added in v0.250905.1
func Validate() error
Validate runs deferred validations on the default CommandLine FlagSet.
func Var ¶
Var defines a flag with the specified name and usage string. The type and value of the flag are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a flag that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.
func Visit ¶
func Visit(fn func(*Flag))
Visit visits the command-line flags in lexicographical order, calling fn for each. It visits only those flags that have been set.
Types ¶
type ByteSize ¶ added in v0.250905.1
type ByteSize int64
ByteSize represents a size in bytes (supports K, M, G, T suffixes incl. KiB style).
type ErrorHandling ¶
type ErrorHandling int
ErrorHandling defines how FlagSet.Parse behaves if the parse fails.
const ( ContinueOnError ErrorHandling = iota // Return a descriptive error. ExitOnError // Call os.Exit(2). PanicOnError // Call panic with a descriptive error. )
These constants cause FlagSet.Parse to behave as described if the parse fails.
type FieldHandler ¶ added in v0.250905.1
type FieldHandler func(ctx *StructFieldContext) (handled bool, err error)
FieldHandler registers a flag for a struct field. It should apply the default value (considering required/default tags) and call the appropriate Var/XXXVar function. It returns true if it handled the field type.
type Flag ¶
type Flag struct {
Name string // name as it appears on command line
Usage string // help message
Value Value // value as set
DefValue string // default value (as text); for usage message
Sensitive bool // mask in usage / error output
}
A Flag represents the state of a flag.
type FlagMeta ¶ added in v0.250905.1
type FlagMeta struct {
Name string `json:"name"`
Usage string `json:"usage"`
Default string `json:"default"`
Value string `json:"value"`
Set bool `json:"set"`
Source string `json:"source"`
Sensitive bool `json:"sensitive"`
}
FlagMeta represents introspection metadata for a single flag.
func Introspect ¶ added in v0.250905.1
func Introspect() []FlagMeta
Introspect returns metadata for the default CommandLine FlagSet.
type FlagSet ¶
type FlagSet struct {
// Usage is the function called when an error occurs while parsing flags.
// The field is a function (not a method) that may be changed to point to
// a custom error handler.
Usage func()
// contains filtered or unexported fields
}
A FlagSet represents a set of defined flags. The zero value of a FlagSet has no name and has ContinueOnError error handling.
func NewFlagSet ¶
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet
NewFlagSet returns a new, empty flag set with the specified name and error handling property.
func NewFlagSetWithEnvPrefix ¶
func NewFlagSetWithEnvPrefix(name string, prefix string, errorHandling ErrorHandling) *FlagSet
NewFlagSetWithEnvPrefix returns a new empty flag set with the specified name, environment variable prefix, and error handling property.
func (*FlagSet) Arg ¶
Arg returns the i'th argument. Arg(0) is the first remaining argument after flags have been processed. Arg returns an empty string if the requested element does not exist.
func (*FlagSet) Bool ¶
Bool defines a bool flag with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the flag.
func (*FlagSet) BoolVar ¶
BoolVar defines a bool flag with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the flag.
func (*FlagSet) ByteSizeFlag ¶ added in v0.250905.1
ByteSizeFlag defines a ByteSize flag and returns a pointer to it.
func (*FlagSet) ByteSizeVar ¶ added in v0.250905.1
Helper registration methods for extended types
func (*FlagSet) DecimalVar ¶ added in v0.250905.1
func (*FlagSet) Deferred ¶ added in v0.250905.1
Deferred queues a validation or post-processing function executed by Validate() (or automatically after ParseStruct when AutoParse is true). Use for custom handlers that need final values after all precedence layers.
func (*FlagSet) Deprecate ¶ added in v0.250905.1
Deprecate marks a flag as deprecated. If replacement is non-empty it is suggested.
func (*FlagSet) Duration ¶
Duration defines a time.Duration flag with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the flag. The flag accepts a value acceptable to time.ParseDuration.
func (*FlagSet) DurationSlice ¶ added in v0.250905.1
func (*FlagSet) DurationSliceVar ¶ added in v0.250905.1
func (*FlagSet) DurationVar ¶
DurationVar defines a time.Duration flag with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the flag. The flag accepts a value acceptable to time.ParseDuration.
func (*FlagSet) EnumVar ¶ added in v0.250905.1
EnumVar registers an enum string flag restricted to the provided allowed values.
func (*FlagSet) Float64 ¶
Float64 defines a float64 flag with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the flag.
func (*FlagSet) Float64Var ¶
Float64Var defines a float64 flag with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the flag.
func (*FlagSet) Init ¶
func (f *FlagSet) Init(name string, errorHandling ErrorHandling)
Init sets the name and error handling property for a flag set. By default, the zero FlagSet uses an empty name, EnvironmentPrefix, and the ContinueOnError error handling policy.
func (*FlagSet) Int ¶
Int defines an int flag with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the flag.
func (*FlagSet) Int64 ¶
Int64 defines an int64 flag with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the flag.
func (*FlagSet) Int64Var ¶
Int64Var defines an int64 flag with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the flag.
func (*FlagSet) IntVar ¶
IntVar defines an int flag with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the flag.
func (*FlagSet) Introspect ¶ added in v0.250905.1
Introspect returns metadata for all registered flags (sorted by name).
func (*FlagSet) JSON ¶ added in v0.250905.1
func (f *FlagSet) JSON(name string, value json.RawMessage, usage string) *json.RawMessage
func (*FlagSet) JSONVar ¶ added in v0.250905.1
func (f *FlagSet) JSONVar(p *json.RawMessage, name string, value json.RawMessage, usage string)
func (*FlagSet) Lookup ¶
Lookup returns the Flag structure of the named flag, returning nil if none exists.
func (*FlagSet) MarkSensitive ¶ added in v0.250905.1
MarkSensitive marks one or more flag names as sensitive causing their values to be masked in usage output and error messages.
func (*FlagSet) OnChange ¶ added in v0.250905.1
OnChange registers a callback invoked when the named flag's value changes due to hot reload. The callback receives the new string representation (masked not applied; caller should treat sensitive values carefully).
func (*FlagSet) Parse ¶
Parse parses flag definitions from the argument list, which should not include the command name. Must be called after all flags in the FlagSet are defined and before flags are accessed by the program. The return value will be ErrHelp if -help or -h were set but not defined.
func (*FlagSet) ParseEnv ¶
ParseEnv parses flags from environment variables. Flags already set will be ignored.
func (*FlagSet) ParseFile ¶
ParseFile parses flags from the file in path. Same format as commandline argumens, newlines and lines beginning with a "#" charater are ignored. Flags already set will be ignored.
func (*FlagSet) ParseSecretDir ¶ added in v0.250905.1
ParseSecretDir ingests secret values from a directory where each file's name maps to a flag name (case-insensitive). Filename transformations tried in order: 1. raw lower-case filename 2. lower-case with '_' replaced by '-' Existing (already set) flags are not overridden. Subdirectories are ignored.
func (*FlagSet) PrintDefaults ¶
func (f *FlagSet) PrintDefaults()
PrintDefaults prints to standard error the default values of all defined command-line flags in the set. See the documentation for the global function PrintDefaults for more information.
func (*FlagSet) SetOutput ¶
SetOutput sets the destination for usage and error messages. If output is nil, os.Stderr is used.
func (*FlagSet) StartWatcher ¶ added in v0.250905.1
StartWatcher enables hot reload for the provided secret directory and/or config file. Pass empty strings to skip either. It is safe to call multiple times; subsequent calls update watched paths.
func (*FlagSet) StopWatcher ¶ added in v0.250905.1
StopWatcher stops hot reload watching.
func (*FlagSet) String ¶
String defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.
func (*FlagSet) StringMapVar ¶ added in v0.250905.1
func (*FlagSet) StringSlice ¶ added in v0.250905.1
func (*FlagSet) StringSliceVar ¶ added in v0.250905.1
func (*FlagSet) StringVar ¶
StringVar defines a string flag with specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.
func (*FlagSet) TimeSliceVar ¶ added in v0.250905.1
func (f *FlagSet) TimeSliceVar(p *[]time.Time, name, sep, layout string, value []time.Time, usage string)
TimeSliceVar registers a []time.Time flag using provided layout (default RFC3339) and separator.
func (*FlagSet) Uint ¶
Uint defines a uint flag with specified name, default value, and usage string. The return value is the address of a uint variable that stores the value of the flag.
func (*FlagSet) Uint64 ¶
Uint64 defines a uint64 flag with specified name, default value, and usage string. The return value is the address of a uint64 variable that stores the value of the flag.
func (*FlagSet) Uint64Var ¶
Uint64Var defines a uint64 flag with specified name, default value, and usage string. The argument p points to a uint64 variable in which to store the value of the flag.
func (*FlagSet) UintVar ¶
UintVar defines a uint flag with specified name, default value, and usage string. The argument p points to a uint variable in which to store the value of the flag.
func (*FlagSet) Validate ¶ added in v0.250905.1
Validate executes deferred validations when ParseStruct was invoked with AutoParse=false. It can be called multiple times; validations execute only once unless new ones were appended.
func (*FlagSet) Var ¶
Var defines a flag with the specified name and usage string. The type and value of the flag are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a flag that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.
type Getter ¶
type Getter interface {
Value
Get() interface{}
}
Getter is an interface that allows the contents of a Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.
type MultiError ¶ added in v0.250905.1
type MultiError struct {
// contains filtered or unexported fields
}
MultiError aggregates multiple validation errors deterministically.
func (*MultiError) Append ¶ added in v0.250905.1
func (m *MultiError) Append(err error)
Append adds a non-nil error.
func (*MultiError) Error ¶ added in v0.250905.1
func (m *MultiError) Error() string
Error implements error.
func (*MultiError) Errors ¶ added in v0.250905.1
func (m *MultiError) Errors() []error
Errors returns a copy of the underlying errors slice.
func (*MultiError) HasErrors ¶ added in v0.250905.1
func (m *MultiError) HasErrors() bool
HasErrors returns true if at least one error recorded.
func (*MultiError) Unwrap ¶ added in v0.250905.1
func (m *MultiError) Unwrap() []error
Unwrap returns the underlying errors slice to support errors.Is / errors.As style matching introduced in Go 1.20+ which walks multiple errors when Unwrap() []error is provided.
type ParseStructOptions ¶ added in v0.250905.1
type ParseStructOptions struct{ AutoParse bool }
ParseStructOptions controls ParseStruct behavior.
type StructFieldContext ¶ added in v0.250905.1
type StructFieldContext struct {
FS *FlagSet
Field reflect.StructField
Value reflect.Value
FlagName string
Help string
Required bool
Sensitive bool
Deprecated string
DefaultTag string
Tags map[string]string // raw tag values (layout, sep, enum, etc.)
}
StructFieldContext provides information & helpers for a struct field registration.
type Value ¶
Value is the interface to the dynamic value stored in a flag. (The default value is represented as a string.)
If a Value has an IsBoolFlag() bool method returning true, the command-line parser makes -name equivalent to -name=true rather than using the next command-line argument.
Set is called once, in command line order, for each flag present.