flag

package module
v0.250905.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 4, 2025 License: BSD-3-Clause Imports: 20 Imported by: 0

README

Flag

An extended, drop‑in replacement for Go's standard flag package originally forked from namsral/flag and enhanced with:

  • Multi-source configuration with layered precedence
  • Automatic struct-based flag registration (ParseStruct)
  • Secret directory ingestion (-secret-dir) and @file indirection for values
  • Extended types (time, decimal, UUID, IP/CIDR, URL, ByteSize, slices, maps, regex, JSON raw, enums, duration & time slices, etc.)
  • Environment variable prefix support
  • Enum validation via struct tags
  • Zero external runtime dependencies beyond a few well-known libraries (uuid, decimal)

If you follow the twelve-factor app methodology this package supports the third factor: store config in the environment—while also adding secure secret file loading and ergonomics for complex configuration surfaces.


Quick Start

package main

import (
    "fmt"
    "log"
    flag "github.com/machship/flag"
)

func main() {
    var age int
    flag.IntVar(&age, "age", 0, "age of gopher")
    flag.Parse()
    fmt.Println("age:", age)
}
go run main.go -age 1   # CLI
export AGE=2; go run main.go   # ENV
echo 'age 3' > cfg.conf; go run main.go -config cfg.conf   # File

Precedence (highest wins)

  1. Command line flags
  2. Environment variables
  3. Secret directory files (-secret-dir if set)
  4. Configuration file (-config if set)
  5. Declared / struct defaults (or zero values)

ParseStruct: Declarative Flag Registration

ParseStruct(ptr) reflects over a struct and auto-registers flags based on field tags. After registration it calls the global Parse(), applying the same layered precedence, then validates required flags.

Supported struct tags:

Tag Purpose Example
flag Flag name (required to participate) Host string `flag:"host"`
default Default value (ignored if required:"true") Port int `flag:"port" default:"8080"`
help Usage/help text Debug bool `flag:"debug" help:"enable debug"`
required Mark as required (true/false) APIKey string `flag:"api-key" required:"true"`
enum Comma list of allowed values (string only) Mode string `flag:"mode" enum:"dev,staging,prod"`
sep Separator for slice flags (default ",") List []string `flag:"list" default:"a,b" sep:";"`
layout time.Time parse layout (default RFC3339) Start time.Time `flag:"start" layout:"2006-01-02"`
sensitive Mask value in usage, errors, introspection Password string `flag:"password" sensitive:"true"`
min Minimum numeric value or min length (string/slice/map) Retries int `flag:"retries" min:"1"`
max Maximum numeric value or max length (string/slice/map) Retries int `flag:"retries" max:"10"`
pattern Regular expression a string must match Name string `flag:"name" pattern:"^[a-z0-9_-]+$"`
deprecated Mark deprecated; value is replacement name or message Old string `flag:"old" deprecated:"new"`

Example:

type Config struct {
        SecretDir string            `flag:"secret-dir" default:"/run/secrets" help:"directory of secret files"`
        Config    string            `flag:"config" help:"optional config file"`
        Host      string            `flag:"host" default:"localhost"`
        Port      int               `flag:"port" default:"8080"`
        Debug     bool              `flag:"debug" required:"true"`
        Mode      string            `flag:"mode" enum:"dev,staging,prod" default:"dev"`
        Timeout   time.Duration     `flag:"timeout" default:"5s"`
        Start     time.Time         `flag:"start" layout:"2006-01-02" default:"2025-09-04"`
        Tags      []string          `flag:"tags" default:"alpha,beta" sep:","`
        Delays    []time.Duration   `flag:"delays" default:"100ms,250ms"`
        Meta      map[string]string `flag:"meta" default:"region=us,team=core"`
        Pattern   *regexp.Regexp    `flag:"pattern" default:"^user_[0-9]+$"`
        JSONBlob  json.RawMessage   `flag:"json" default:"{\"enabled\":true}"`
        ID        uuid.UUID         `flag:"id" default:"00000000-0000-0000-0000-000000000000"`
        Price     decimal.Decimal   `flag:"price" default:"12.99"`
        CIDR      net.IPNet         `flag:"cidr" default:"10.0.0.0/24"`
        URL       neturl.URL        `flag:"endpoint" default:"https://api.example.com"`
        Limit     ByteSize          `flag:"limit" default:"10MB" help:"memory limit"`
}

var cfg Config
if err := flag.ParseStruct(&cfg); err != nil { log.Fatal(err) }
Supported Types

Primitive & standard: bool, int, int64, uint, uint64, float64, string, time.Duration

Extended:

  • time.Time (with layout tag)
  • []time.Time (with layout tag & optional sep; see Time Slice Flags)
  • decimal.Decimal (github.com/shopspring/decimal)
  • uuid.UUID
  • net.IP, net.IPNet (CIDR)
  • net/url.URL
  • ByteSize (human sizes: 512B, 10KB, 1MiB, 2G, 5GiB ...)
  • big.Int, big.Rat
  • []string, []time.Duration
  • map[string]string (default string like k=v,k2=v2)
  • json.RawMessage (validated on default parse)
  • *regexp.Regexp
  • String enums via enum:"a,b,c"
  • Validated strings via pattern:"^regex$"

Unsupported types trigger an error referencing the field.

Secret Directory Support (-secret-dir)

If a flag named secret-dir (or the value of flag.DefaultSecretDirFlagname) is set (CLI, env, or default), every regular file in that directory is considered a potential flag value.

Filename → flag name resolution tries:

  1. Lower-case filename
  2. Lower-case with underscores converted to dashes

Rules:

  • Existing values (set by CLI or env) are NOT overridden
  • Empty file for a bool flag sets it to true
  • Contents are trimmed of one trailing newline
  • A value starting with @path is replaced by the referenced file's contents (use @@ to escape a literal @)

Example layout:

/run/secrets/
    db-user        => "alice"\n
    db-pass        => "@/run/secure/pass.txt"   (indirection)
    DEBUG          => ""  (sets -debug)
type C struct {
    SecretDir string `flag:"secret-dir" default:"/run/secrets"`
    DBUser    string `flag:"db-user" required:"true"`
    DBPass    string `flag:"db-pass" required:"true"`
    Debug     bool   `flag:"debug"`
}
var c C
if err := flag.ParseStruct(&c); err != nil { log.Fatal(err) }

@file Indirection

Anywhere a value is accepted (CLI, env, config file, secret file) you can supply @/path/to/file to load the value from that file. Use @@ to escape.

Input Example Result
CLI -password @/run/secret/pass flag value becomes file contents
Env PASSWORD=@/run/secret/pass same
Config file password @/run/secret/pass same
Secret file file contains @/path nested expansion

ByteSize Type

Human-friendly sizes with decimal (KB=1000) or binary (KiB=1024) units.

Examples: 512B, 128K, 10KB, 12MiB, 1G, 2GiB, 5TB, 3TiB.

var limit flag.ByteSize
flag.ByteSizeVar(&limit, "limit", 0, "memory limit")

Enum Flags

type C struct {
    Mode string `flag:"mode" enum:"dev,staging,prod" default:"dev"`
}

Invalid values produce an error listing allowed values.

Validation Tags

Validation is deferred until after all precedence layers are applied, so the final value (from CLI, env, secret, config or default) is checked.

Supported tags:

  • min / max – apply to numeric types OR length (string, slice, map)
  • pattern – Go regexp applied to string value

Multiple failures aggregate into a single error (joined with ; ) via an internal multi-error collector (MultiError).

type C struct {
    Port int    `flag:"port" default:"8080" min:"1" max:"65535"`
    Name string `flag:"name" pattern:"^[a-z0-9_-]{3,32}$"`
}

Sensitive Values

Mark secrets so they are masked in:

  • Usage output (default values show as ******)
  • Error messages (actual provided secret value suppressed)
  • Introspection metadata
type Secrets struct {
    Password string `flag:"password" required:"true" sensitive:"true"`
}

You can also mark flags programmatically: flag.MarkSensitive("password").

Introspection API

Programmatically inspect all registered flags and their provenance:

metas := flag.Introspect()
for _, m := range metas {
    fmt.Printf("%s: set=%v source=%s value=%q sensitive=%v\n", m.Name, m.Set, m.Source, m.Value, m.Sensitive)
}

Source is one of: cli, env, secret, config, or default. Sensitive values are masked as ****** (value & default).

Disabling Auto Parse

ParseStruct automatically calls flag.Parse() after registration. To decouple registration and parsing (e.g., to add more flags manually, or defer to a subcommand decision) use:

var cfg Config
if err := flag.ParseStructWithOptions(&cfg, flag.ParseStructOptions{AutoParse:false}); err != nil { log.Fatal(err) }
// later
flag.Parse()
if err := flag.Validate(); err != nil { log.Fatal(err) }

Validate() executes deferred validations and returns aggregated errors (if any).

Nested Structs & Prefixing

ParseStruct recurses into exported nested struct fields even when they lack a flag tag; their inner fields with flag tags are registered.

You can apply a prefix to all flags in a nested struct using a flagPrefix tag on the nested struct field. Prefixes are concatenated with dots.

type DBConfig struct {
    Host string `flag:"host" default:"localhost"`
    Port int    `flag:"port" default:"5432"`
}
type App struct {
    DB DBConfig `flagPrefix:"db"`
    Cache struct {
        Size int `flag:"size" default:"128"`
    } `flagPrefix:"cache"`
}

Flags registered:

 -db.host   (default localhost)
 -db.port   (default 5432)
 -cache.size (default 128)

Nested prefixes compose; an inner struct with flagPrefix:"inner" under a parent with flagPrefix:"outer" yields flags like -outer.inner.field.

Provenance / Sources

Each flag stores the source that supplied its final value. This is exposed via introspection; you can build diagnostics or config dumps that omit secrets but still show origin.

Example (with a sensitive password read from env):

password: set=true source=env value="******" sensitive=true
host: set=false source=default value="localhost" sensitive=false

Error Aggregation

When multiple validation errors occur they are combined into a single returned error (implementing error). The concrete type is *flag.MultiError which also implements:

  • Errors() []error – returns the individual errors
  • Unwrap() []error – Go's multi-error unwrapping, allowing errors.Is / errors.As to match any constituent error

Example:

if err := flag.ParseStruct(&cfg); err != nil {
    var me *flag.MultiError
    if errors.As(err, &me) {
        for _, e := range me.Errors() { fmt.Println("validation:", e) }
    }
    return err
}

Deprecation

Mark flags as deprecated with a struct tag or programmatically:

type Opts struct {
    Old string `flag:"old" deprecated:"new"` // suggests replacement
    Legacy int  `flag:"legacy" deprecated:"(will be removed)"`
}

First use prints a one-time warning:

warning: flag -old is deprecated, use -new instead
warning: flag -legacy is deprecated (will be removed)

Programmatic: flag.Deprecate("old", "new").

Time Slice Flags

[]time.Time flags parse comma (or custom sep) separated values. Layout defaults to RFC3339 unless layout tag provided.

type Schedule struct {
    Windows []time.Time `flag:"windows" layout:"2006-01-02" default:"2025-09-05,2025-09-06"`
}

CLI: -windows 2025-09-05,2025-09-06

Cross-field / Post-parse Validation (Deferred)

Use flag.Deferred(func() error { ... }) inside custom handlers or after manual registration to run logic after all precedence layers (CLI > env > secret > config > defaults) have settled. This is useful for:

  • Cross-field consistency checks (e.g. start < end)
  • Decoding multi-part derived values
  • Expensive validations you only want once

Example:

type Range struct {
    Start time.Time `flag:"start" layout:"2006-01-02" required:"true"`
    End   time.Time `flag:"end" layout:"2006-01-02" required:"true"`
}
var r Range
if err := flag.ParseStruct(&r); err != nil { log.Fatal(err) }
flag.Deferred(func() error { // or register before ParseStruct with AutoParse:false
    if !r.End.After(r.Start) { return fmt.Errorf("end must be after start") }
    return nil
})
if err := flag.Validate(); err != nil { log.Fatal(err) }

If you use ParseStruct with default AutoParse:true, deferred funcs added during struct handling execute automatically; any you add afterwards require calling flag.Validate().

Programmatic API Summary

Beyond the standard library-compatible surface, the following helpers are provided:

  • Sources / layering: ParseStruct, ParseStructWithOptions, Validate
  • Introspection: Introspect() -> []FlagMeta
  • Sensitivity: MarkSensitive(names...)
  • Deprecation: Deprecate(name, replacement) (also via struct tag deprecated)
  • Hot reload: StartWatcher(secretDir, configFile), StopWatcher(), OnChange(flagName, func(string))
  • Custom struct types: RegisterStructHandler(reflect.Type, FieldHandler) + StructFieldContext
  • Deferred post-parse hooks: Deferred(func() error)
  • Extended type registration helpers: TimeVar, TimeSliceVar, ByteSizeVar, DecimalVar, IPVar, IPNetVar, URLVar, UUIDVar, BigIntVar, BigRatVar, RegexpVar, StringSliceVar, DurationSliceVar, TimeSliceVar, StringMapVar, JSONVar, EnumVar
  • Environment prefix: NewFlagSetWithEnvPrefix(name, prefix, handling) (uses APP_ style names)

All of these augment (not replace) the original flag package patterns; you can mix and match incrementally.

Struct Field Handler Registry

Extend ParseStruct with custom types by registering a handler:

type Base64String string

func init() {
    flag.RegisterStructHandler(reflect.TypeOf(Base64String("")), func(ctx *flag.StructFieldContext) (bool, error) {
        def := ctx.Value.String()
        if ctx.DefaultTag != "" { def = ctx.DefaultTag }
        var raw string = def
        flag.StringVar(&raw, ctx.FlagName, raw, ctx.Help)
        // deferred decode after precedence layers settled
        flag.Deferred(func() error {
            if raw == "" { return nil }
            b, err := base64.StdEncoding.DecodeString(raw)
            if err != nil { return fmt.Errorf("invalid base64 for -%s: %w", ctx.FlagName, err) }
            *(*Base64String)(ctx.Value.Addr().Interface().(*Base64String)) = Base64String(b)
            return nil
        })
        return true, nil
    })
}

Handler API:

  • RegisterStructHandler(reflect.Type, FieldHandler)
  • FieldHandler returns (handled bool, err error)
  • StructFieldContext carries tags (DefaultTag, Deprecated, etc.)

Generic Numeric Values

All numeric flag types now share a generic implementation internally; public APIs (IntVar, Uint64Var, etc.) are unchanged. Avoid reflecting on internal unexported Value concrete types.

Hot Reload & OnChange Callbacks

You can watch a secret directory and/or a config file for changes and react when specific flag values change.

flag.StartWatcher("/run/secrets", "/app/config.conf")
flag.OnChange("db-password", func(v string) {
    // v is the new string value (be careful with sensitive data)
    reloadDB(v)
})
defer flag.StopWatcher()

Behavior:

  • Secret dir watch: any file modification/add triggers re-read of that directory via ParseSecretDir (existing CLI/env values still win and are not overridden).
  • Config file watch: file change triggers re-parse of config file layer (only flags originally sourced from config layer or still unset are updated).
  • Only differences dispatch callbacks (per flag). Callbacks run in watcher goroutine; they are recovered on panic.
  • Sensitive flags are passed in plain form to callbacks; handle securely.

Limitations / Notes:

  • Environment variable changes are not automatically detected (exported env cannot be watched portably).
  • Debouncing is not currently implemented—rapid successive writes may emit multiple callbacks.
  • CLI-provided values are never overwritten by hot reload.

Slices & Maps

Type Declaration Default Tag Example
[]string Tags []string `flag:"tags" sep:","` default:"a,b,c"
[]time.Duration Delays []time.Duration `flag:"delays"` default:"100ms,1s"
[]time.Time Times []time.Time `flag:"times" layout:"2006-01-02T15:04:05Z07:00"` default:"2025-09-05T10:00:00Z,2025-09-05T12:00:00Z"
map[string]string Meta map[string]string `flag:"meta"` default:"k=v,team=core"

sep controls splitting for slices (default ","). Map defaults expect k=v comma separated pairs.

Configuration File Format

Plain text, one flag per line:

key value
key=value
booleanFlag
# comments and blank lines ignored

Environment Variables

Name is the flag name upper-cased, dashes replaced by underscores. Optional prefix via NewFlagSetWithEnvPrefix.

fs := flag.NewFlagSetWithEnvPrefix(os.Args[0], "APP", flag.ContinueOnError)
fs.String("db-host", "localhost", "db host")
// Parses APP_DB_HOST

Extended Example End-to-End

type Config struct {
    SecretDir string        `flag:"secret-dir" default:"./secrets"`
    Config    string        `flag:"config"`
    Host      string        `flag:"host" default:"localhost"`
    Port      int           `flag:"port" default:"8080"`
    Mode      string        `flag:"mode" enum:"dev,staging,prod" default:"dev"`
    Timeout   time.Duration `flag:"timeout" default:"5s"`
    Limits    []time.Duration `flag:"limits" default:"100ms,200ms,500ms"`
    SizeLimit flag.ByteSize `flag:"limit" default:"256MiB"`
}

var cfg Config
if err := flag.ParseStruct(&cfg); err != nil { log.Fatal(err) }

Populate via (in ascending precedence):

  • Default tag values
  • config file (if provided)
  • Secret dir files (if secret-dir set)
  • Environment variables (e.g. PORT=9000)
  • CLI flags (-port 9000)

Migration From namsral/flag

Most code will continue to compile unchanged. New features are opt‑in:

  • Add ParseStruct instead of manually declaring many flags
  • Add a secret-dir flag for secret ingestion
  • Use @file syntax to externalize sensitive values
  • Leverage additional types and enums without extra boilerplate

Examples

See the examples directory for simple usage patterns. Tests in the repository exercise advanced features (secret dir, struct parsing, indirection).

License


Copyright (c) 2012 The Go Authors. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

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.
}
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.
}

Index

Examples

Constants

This section is empty.

Variables

View Source
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.

View Source
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.

View Source
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.

View Source
var EnvironmentPrefix = ""

EnvironmentPrefix defines a string that will be implicitely prefixed to a flag name before looking it up in the environment variables.

View Source
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.

View Source
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

func Arg(i int) string

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 Args

func Args() []string

Args returns the non-flag command-line arguments.

func BigInt added in v0.250905.1

func BigInt(name string, value *big.Int, usage string) *big.Int

func BigIntVar added in v0.250905.1

func BigIntVar(p *big.Int, name string, value *big.Int, usage string)

func BigRat added in v0.250905.1

func BigRat(name string, value *big.Rat, usage string) *big.Rat

func BigRatVar added in v0.250905.1

func BigRatVar(p *big.Rat, name string, value *big.Rat, usage string)

func Bool

func Bool(name string, value bool, usage string) *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

func BoolVar(p *bool, name string, value bool, usage string)

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 ByteSizeVar(p *ByteSize, name string, value ByteSize, usage string)

func Decimal added in v0.250905.1

func Decimal(name string, value decimal.Decimal, usage string) *decimal.Decimal

func DecimalVar added in v0.250905.1

func DecimalVar(p *decimal.Decimal, name string, value decimal.Decimal, usage string)

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

func Duration(name string, value time.Duration, usage string) *time.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 DurationSlice(name, sep string, value []time.Duration, usage string) *[]time.Duration

func DurationSliceVar added in v0.250905.1

func DurationSliceVar(p *[]time.Duration, name, sep string, value []time.Duration, usage string)

func DurationVar

func DurationVar(p *time.Duration, name string, value time.Duration, usage string)

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 Enum added in v0.250905.1

func Enum(name string, value string, allowed []string, usage string) *string

func EnumVar added in v0.250905.1

func EnumVar(p *string, name string, value string, allowed []string, usage string)

func Float64

func Float64(name string, value float64, usage string) *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

func Float64Var(p *float64, name string, value float64, usage string)

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 IP added in v0.250905.1

func IP(name string, value net.IP, usage string) *net.IP

func IPNet added in v0.250905.1

func IPNet(name string, value *net.IPNet, usage string) *net.IPNet

func IPNetVar added in v0.250905.1

func IPNetVar(p *net.IPNet, name string, value *net.IPNet, usage string)

func IPVar added in v0.250905.1

func IPVar(p *net.IP, name string, value net.IP, usage string)

func Int

func Int(name string, value int, usage string) *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

func Int64(name string, value int64, usage string) *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

func Int64Var(p *int64, name string, value int64, usage string)

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

func IntVar(p *int, name string, value int, usage string)

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 NFlag

func NFlag() int

NFlag returns the number of command-line flags that have been set.

func OnChange added in v0.250905.1

func OnChange(name string, fn func(string))

OnChange adds a callback to the default FlagSet.

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

func ParseStruct(s any) error

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 Parsed

func Parsed() bool

Parsed reports whether the command-line flags have been parsed.

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 Regexp added in v0.250905.1

func Regexp(name string, value *regexp.Regexp, usage string) **regexp.Regexp

func RegexpVar added in v0.250905.1

func RegexpVar(p **regexp.Regexp, name string, value *regexp.Regexp, usage string)

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 Set

func Set(name, value string) error

Set sets the value of the named command-line flag.

func StartWatcher added in v0.250905.1

func StartWatcher(secretDir, configFile string) error

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

func String(name string, value string, usage string) *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 StringMap added in v0.250905.1

func StringMap(name string, value map[string]string, usage string) *map[string]string

func StringMapVar added in v0.250905.1

func StringMapVar(p *map[string]string, name string, value map[string]string, usage string)

func StringSlice added in v0.250905.1

func StringSlice(name, sep string, value []string, usage string) *[]string

func StringSliceVar added in v0.250905.1

func StringSliceVar(p *[]string, name, sep string, value []string, usage string)

func StringVar

func StringVar(p *string, name string, value string, usage string)

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 Time added in v0.250905.1

func Time(name, layout string, value time.Time, usage string) *time.Time

func TimeSlice added in v0.250905.1

func TimeSlice(name, sep, layout string, value []time.Time, usage string) *[]time.Time

func TimeSliceVar added in v0.250905.1

func TimeSliceVar(p *[]time.Time, name, sep, layout string, value []time.Time, usage string)

func TimeVar added in v0.250905.1

func TimeVar(p *time.Time, name, layout string, value time.Time, usage string)

func URL added in v0.250905.1

func URL(name string, value *neturl.URL, usage string) *neturl.URL

func URLVar added in v0.250905.1

func URLVar(p *neturl.URL, name string, value *neturl.URL, usage string)

func UUID added in v0.250905.1

func UUID(name string, value uuid.UUID, usage string) *uuid.UUID

func UUIDVar added in v0.250905.1

func UUIDVar(p *uuid.UUID, name string, value uuid.UUID, usage string)

func Uint

func Uint(name string, value uint, usage string) *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

func Uint64(name string, value uint64, usage string) *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

func Uint64Var(p *uint64, name string, value uint64, usage string)

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

func UintVar(p *uint, name string, value uint, usage string)

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

func UnquoteUsage(flag *Flag) (name string, usage string)

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

func Var(value Value, name string, usage string)

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.

func VisitAll

func VisitAll(fn func(*Flag))

VisitAll visits the command-line flags in lexicographical order, calling fn for each. It visits all flags, even those not set.

func WithArgs added in v0.250905.1

func WithArgs(args []string, fn func() error) error

WithArgs temporarily sets os.Args, reparses flags, runs fn, then restores state. Flags must be re-registered prior to calling if required.

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).

func ByteSizeFlag added in v0.250905.1

func ByteSizeFlag(name string, value ByteSize, usage string) *ByteSize

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.

func Lookup

func Lookup(name string) *Flag

Lookup returns the Flag structure of the named command-line flag, returning nil if none exists.

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

func (f *FlagSet) Arg(i int) string

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) Args

func (f *FlagSet) Args() []string

Args returns the non-flag arguments.

func (*FlagSet) BigInt added in v0.250905.1

func (f *FlagSet) BigInt(name string, value *big.Int, usage string) *big.Int

func (*FlagSet) BigIntVar added in v0.250905.1

func (f *FlagSet) BigIntVar(p *big.Int, name string, value *big.Int, usage string)

func (*FlagSet) BigRat added in v0.250905.1

func (f *FlagSet) BigRat(name string, value *big.Rat, usage string) *big.Rat

func (*FlagSet) BigRatVar added in v0.250905.1

func (f *FlagSet) BigRatVar(p *big.Rat, name string, value *big.Rat, usage string)

func (*FlagSet) Bool

func (f *FlagSet) Bool(name string, value bool, usage string) *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

func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string)

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

func (f *FlagSet) ByteSizeFlag(name string, value ByteSize, usage string) *ByteSize

ByteSizeFlag defines a ByteSize flag and returns a pointer to it.

func (*FlagSet) ByteSizeVar added in v0.250905.1

func (f *FlagSet) ByteSizeVar(p *ByteSize, name string, value ByteSize, usage string)

Helper registration methods for extended types

func (*FlagSet) Decimal added in v0.250905.1

func (f *FlagSet) Decimal(name string, value decimal.Decimal, usage string) *decimal.Decimal

func (*FlagSet) DecimalVar added in v0.250905.1

func (f *FlagSet) DecimalVar(p *decimal.Decimal, name string, value decimal.Decimal, usage string)

func (*FlagSet) Deferred added in v0.250905.1

func (f *FlagSet) Deferred(fn func() error)

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

func (f *FlagSet) Deprecate(name, replacement string)

Deprecate marks a flag as deprecated. If replacement is non-empty it is suggested.

func (*FlagSet) Duration

func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.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 (f *FlagSet) DurationSlice(name, sep string, value []time.Duration, usage string) *[]time.Duration

func (*FlagSet) DurationSliceVar added in v0.250905.1

func (f *FlagSet) DurationSliceVar(p *[]time.Duration, name, sep string, value []time.Duration, usage string)

func (*FlagSet) DurationVar

func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string)

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) Enum added in v0.250905.1

func (f *FlagSet) Enum(name string, value string, allowed []string, usage string) *string

func (*FlagSet) EnumVar added in v0.250905.1

func (f *FlagSet) EnumVar(p *string, name string, value string, allowed []string, usage string)

EnumVar registers an enum string flag restricted to the provided allowed values.

func (*FlagSet) Float64

func (f *FlagSet) Float64(name string, value float64, usage string) *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

func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string)

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) IP added in v0.250905.1

func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP

func (*FlagSet) IPNet added in v0.250905.1

func (f *FlagSet) IPNet(name string, value *net.IPNet, usage string) *net.IPNet

func (*FlagSet) IPNetVar added in v0.250905.1

func (f *FlagSet) IPNetVar(p *net.IPNet, name string, value *net.IPNet, usage string)

func (*FlagSet) IPVar added in v0.250905.1

func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string)

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

func (f *FlagSet) Int(name string, value int, usage string) *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

func (f *FlagSet) Int64(name string, value int64, usage string) *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

func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string)

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

func (f *FlagSet) IntVar(p *int, name string, value int, usage string)

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

func (f *FlagSet) Introspect() []FlagMeta

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

func (f *FlagSet) Lookup(name string) *Flag

Lookup returns the Flag structure of the named flag, returning nil if none exists.

func (*FlagSet) MarkSensitive added in v0.250905.1

func (f *FlagSet) MarkSensitive(names ...string)

MarkSensitive marks one or more flag names as sensitive causing their values to be masked in usage output and error messages.

func (*FlagSet) NArg

func (f *FlagSet) NArg() int

NArg is the number of arguments remaining after flags have been processed.

func (*FlagSet) NFlag

func (f *FlagSet) NFlag() int

NFlag returns the number of flags that have been set.

func (*FlagSet) OnChange added in v0.250905.1

func (f *FlagSet) OnChange(name string, fn func(string))

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

func (f *FlagSet) Parse(arguments []string) error

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

func (f *FlagSet) ParseEnv(environ []string) error

ParseEnv parses flags from environment variables. Flags already set will be ignored.

func (*FlagSet) ParseFile

func (f *FlagSet) ParseFile(path string) error

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

func (f *FlagSet) ParseSecretDir(dir string) error

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) Parsed

func (f *FlagSet) Parsed() bool

Parsed reports whether f.Parse has been called.

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) Regexp added in v0.250905.1

func (f *FlagSet) Regexp(name string, value *regexp.Regexp, usage string) **regexp.Regexp

func (*FlagSet) RegexpVar added in v0.250905.1

func (f *FlagSet) RegexpVar(p **regexp.Regexp, name string, value *regexp.Regexp, usage string)

func (*FlagSet) Set

func (f *FlagSet) Set(name, value string) error

Set sets the value of the named flag.

func (*FlagSet) SetOutput

func (f *FlagSet) SetOutput(output io.Writer)

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

func (f *FlagSet) StartWatcher(secretDir, configFile string) error

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

func (f *FlagSet) StopWatcher() error

StopWatcher stops hot reload watching.

func (*FlagSet) String

func (f *FlagSet) String(name string, value string, usage string) *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) StringMap added in v0.250905.1

func (f *FlagSet) StringMap(name string, value map[string]string, usage string) *map[string]string

func (*FlagSet) StringMapVar added in v0.250905.1

func (f *FlagSet) StringMapVar(p *map[string]string, name string, value map[string]string, usage string)

func (*FlagSet) StringSlice added in v0.250905.1

func (f *FlagSet) StringSlice(name, sep string, value []string, usage string) *[]string

func (*FlagSet) StringSliceVar added in v0.250905.1

func (f *FlagSet) StringSliceVar(p *[]string, name, sep string, value []string, usage string)

func (*FlagSet) StringVar

func (f *FlagSet) StringVar(p *string, name string, value string, usage string)

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) Time added in v0.250905.1

func (f *FlagSet) Time(name, layout string, value time.Time, usage string) *time.Time

func (*FlagSet) TimeSlice added in v0.250905.1

func (f *FlagSet) TimeSlice(name, sep, layout string, value []time.Time, usage string) *[]time.Time

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) TimeVar added in v0.250905.1

func (f *FlagSet) TimeVar(p *time.Time, name, layout string, value time.Time, usage string)

func (*FlagSet) URL added in v0.250905.1

func (f *FlagSet) URL(name string, value *neturl.URL, usage string) *neturl.URL

func (*FlagSet) URLVar added in v0.250905.1

func (f *FlagSet) URLVar(p *neturl.URL, name string, value *neturl.URL, usage string)

func (*FlagSet) UUID added in v0.250905.1

func (f *FlagSet) UUID(name string, value uuid.UUID, usage string) *uuid.UUID

func (*FlagSet) UUIDVar added in v0.250905.1

func (f *FlagSet) UUIDVar(p *uuid.UUID, name string, value uuid.UUID, usage string)

func (*FlagSet) Uint

func (f *FlagSet) Uint(name string, value uint, usage string) *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

func (f *FlagSet) Uint64(name string, value uint64, usage string) *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

func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string)

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

func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string)

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

func (f *FlagSet) Validate() error

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

func (f *FlagSet) Var(value Value, name string, usage string)

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 (*FlagSet) Visit

func (f *FlagSet) Visit(fn func(*Flag))

Visit visits the flags in lexicographical order, calling fn for each. It visits only those flags that have been set.

func (*FlagSet) VisitAll

func (f *FlagSet) VisitAll(fn func(*Flag))

VisitAll visits the flags in lexicographical order, calling fn for each. It visits all flags, even those not set.

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

type Value interface {
	String() string
	Set(string) error
}

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL