flagx

package module
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2026 License: MIT Imports: 11 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Flagx

A Go command-line flag parsing library with environment variable support. Command-line flags take priority over environment variables.

Features

  • Built on top of the standard flag package, with consistent API and low learning curve
  • Automatic environment variable support — env var names are derived from flag names
  • Supports --env.prefix for a unified environment variable prefix
  • Rich type support: Duration, Bytes, Text, arrays, and more
  • Secret flag masking to prevent sensitive information leakage
  • Required flag validation
  • Post-parse callbacks (AfterParse)

Installation

go get github.com/cloudfly/flagx

Quick Start

package main

import "github.com/cloudfly/flagx"

var (
    logFile    = flagx.NewString("log.file", "", "path to log file")
    logLevel   = flagx.NewBool("log.level", false, "enable debug logging")
    serverAddr = flagx.NewString("server.addr", ":7070", "HTTP server listen address")
    serverPort = flagx.NewInt("server.port", 8080, "TCP listen port")
)

func main() {
    flagx.Parse()
    // use *logFile, *logLevel, etc.
}

Usage:

# Command-line flags
./app --server.addr=:8080 --server.port=9090

# Environment variables
SERVER_ADDR=:8080 SERVER_PORT=9090 ./app

# Mixed usage (command-line takes priority)
SERVER_ADDR=:8080 ./app --server.port=9090

Flag Types

Basic Types
// Boolean
debug := flagx.NewBool("debug", false, "enable debug mode")

// String
name := flagx.NewString("name", "default", "name of the service")

// Integer
port := flagx.NewInt("port", 8080, "listen port")
port64 := flagx.NewInt64("port64", 8080, "64-bit listen port")

// Float
ratio := flagx.NewFloat("ratio", 0.5, "ratio value")
Duration

Supported time unit suffixes: ms (milliseconds), s (seconds), m (minutes), h (hours), d (days), w (weeks), y (years). Defaults to seconds when no suffix is provided.

Supports combined notation, e.g. 2h5m, 1d6h.

timeout := flagx.NewDuration("timeout", "30s", "request timeout")
days := flagx.NewDuration("retention", "30d", "data retention period in days")
weeks := flagx.NewDuration("interval", "2w", "execution interval")

Usage:

fmt.Println(timeout.Msecs) // milliseconds
Bytes

Supported byte unit suffixes:

Suffix Meaning Base
KB Kilobyte 1000
MB Megabyte 1000
GB Gigabyte 1000
TB Terabyte 1000
KiB Kibibyte 1024
MiB Mebibyte 1024
GiB Gibibyte 1024
TiB Tebibyte 1024
cacheSize := flagx.NewBytes("cache.size", 128, "cache size in bytes")
maxUpload := flagx.NewBytes("upload.max", 64, "max upload size", flagx.Env("MAX_UPLOAD_SIZE"))

Usage:

fmt.Println(cacheSize.N)      // bytes as int64
fmt.Println(cacheSize.IntN()) // bytes as int (auto-truncated)
Text

Used to hold complex content such as JSON or configuration text. The value passed in must be a base64-encoded string, which is automatically decoded during parsing.

config := flagx.NewText("config", "", "configuration content, base64 encoded")

Usage:

// Pass base64-encoded JSON via command line
// echo -n '{"key":"value"}' | base64
./app --config=eyJrZXkiOiJ2YWx1ZSJ9

fmt.Println(config.Value) // decoded original string: {"key":"value"}
Array Types

Array types support two ways of passing values:

  1. Specify the same flag multiple times: --items=a --items=b --items=c
  2. Comma-separated: --items=a,b,c

Supported array types:

// String array
tags := flagx.NewArrayString("tags", "list of tags")

// Integer array
ports := flagx.NewArrayInt("ports", "list of ports")

// Boolean array
flags := flagx.NewArrayBool("flags", "list of boolean flags")

// Duration array
timeouts := flagx.NewArrayDuration("timeouts", "list of timeout values")

// Bytes array
sizes := flagx.NewArrayBytes("sizes", "list of sizes")

// Text array
configs := flagx.NewArrayText("configs", "list of configurations")

Usage:

for _, tag := range *tags {
    fmt.Println(tag)
}

// Convenience method: get value at index, return default if out of bounds
port := ports.GetOptionalArgOrDefault(0, 8080)

Options

All New* functions accept a variadic last parameter opts ...Option for configuring additional flag behavior.

Env — Custom Environment Variable Name

Customize the environment variable name. Multiple names can be specified, and they are tried in order from left to right:

// Default env var name is LOG_FILE
logFile := flagx.NewString("log.file", "", "log file path")

// Custom env var name CUSTOM_LOG_FILE
logFile := flagx.NewString("log.file", "", "log file path", flagx.Env("CUSTOM_LOG_FILE"))

// Multiple env vars, tried in order
logFile := flagx.NewString("log.file", "", "log file path",
    flagx.Env("CUSTOM_LOG_FILE"),
    flagx.Env("SERVER_LOG_PATH"),
    flagx.Env("LOG_PATH"),
)
Required — Required Flag

Marks the flag as required. It must be set via command line or environment variable, otherwise the program exits with an error:

dsn := flagx.NewString("mysql.dsn", "", "MySQL connection string", flagx.Required())
AfterParse — Post-Parse Callback

Sets a function to be called after flag parsing is complete. Useful for post-processing based on the values of other flags.

addr := flagx.NewString("addr", "", "server address", flagx.AfterParse(func(isSet bool, set func(string) error) {
    if !isSet {
        // If addr is not set, set its value via the set function
        set(":8080")
    }
}))

Environment Variable Mechanism

Default Rules

By default, environment variable names are derived from flag names using the following rules:

  • Replace . with _
  • Convert to uppercase

Examples:

  • log.file → LOG_FILE
  • server.port → SERVER_PORT
Unified Prefix

Use the --env.prefix flag to set a unified prefix for all environment variables:

./app --env.prefix=MYAPP_

With this prefix, the env var names become:

  • log.file → MYAPP_LOG_FILE
  • server.port → MYAPP_SERVER_PORT
Precedence

Command-line flags > Environment variables > Default values

Secret Flag Masking

flagx automatically masks flags whose names contain pass, key, secret, or token to prevent sensitive information from leaking in logs or monitoring output.

You can also manually register secret flags:

flagx.RegisterSecretFlag("mysql.dsn")

When iterating via Visit and VisitAll, secret flag values are automatically masked (keeping the first and last 1/4 of characters, replacing the middle with *).

Utility Functions

Parse

Parses command-line flags and environment variables. Must be called before using any flags:

flagx.Parse()
FlagEnvName

Gets the environment variable name corresponding to a flag:

envName := flagx.FlagEnvName("log.file")
// returns "LOG_FILE" by default
// returns "MYAPP_LOG_FILE" when --env.prefix=MYAPP_ is set
Visit / VisitAll
// Iterate over all flags explicitly set via command line
flagx.Visit(func(name, value string) {
    fmt.Printf("%s = %s\n", name, value)
})

// Iterate over all flags (including unset ones)
flagx.VisitAll(func(name, value string) {
    fmt.Printf("%s = %s\n", name, value)
})
WriteFlags

Writes all explicitly set flags to an io.Writer:

flagx.WriteFlags(os.Stdout)
Usage

Prints usage information:

flagx.Usage("My App v1.0.0")

When -h or -help is passed, detailed descriptions of all flags are printed; otherwise, only a hint to use -help is shown.

Full Example

package main

import (
    "fmt"
    "github.com/cloudfly/flagx"
)

var (
    // Basic types
    debug    = flagx.NewBool("debug", false, "enable debug mode")
    appName  = flagx.NewString("app.name", "demo", "application name")
    port     = flagx.NewInt("port", 8080, "listen port", flagx.Env("PORT"))

    // Duration
    timeout  = flagx.NewDuration("timeout", "30s", "request timeout")

    // Bytes
    maxBody  = flagx.NewBytes("http.maxBody", 1024*1024, "max request body size")

    // Array
    allowIPs = flagx.NewArrayString("security.allowIPs", "list of allowed IPs")

    // Required flag
    dsn      = flagx.NewString("mysql.dsn", "", "MySQL connection string", flagx.Required())
)

func main() {
    flagx.Parse()

    fmt.Printf("App: %s\n", *appName)
    fmt.Printf("Port: %d\n", *port)
    fmt.Printf("Debug: %v\n", *debug)
    fmt.Printf("Timeout: %dms\n", timeout.Msecs)
    fmt.Printf("Max Body: %d bytes\n", maxBody.N)
    fmt.Printf("Allow IPs: %v\n", *allowIPs)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DurationValue

func DurationValue(s string, step int64) (int64, error)

DurationValue returns the duration in milliseconds for the given s and the given step.

Duration in s may be combined, i.e. 2h5m, -2h5m or 2h-5m.

The returned duration value can be negative.

func FlagEnvName added in v0.3.0

func FlagEnvName(name string) string

func IsSecretFlag

func IsSecretFlag(s string) bool

IsSecretFlag returns true of s contains flag name with secret value, which shouldn't be exposed.

func NewBool

func NewBool(name string, value bool, usage string, opts ...Option) *bool

NewBool creates a new bool flag.

func NewFloat

func NewFloat(name string, value float64, usage string, opts ...Option) *float64

NewFloat creates a new float64 flag.

func NewInt

func NewInt(name string, value int, usage string, opts ...Option) *int

NewInt creates a new int flag.

func NewInt64

func NewInt64(name string, value int64, usage string, opts ...Option) *int64

NewInt64 creates a new int64 flag.

func NewString

func NewString(name string, value string, usage string, opts ...Option) *string

NewString creates a new string flag.

func Parse

func Parse()

Parse parses environment vars(if env.prefix provided) and command-line flags.

Flags set via command-line override flags set via environment vars.

This function must be called instead of flag.Parse() before using any flags in the program.

func ParseEnv added in v0.3.2

func ParseEnv()

ParseEnv parses environment vars(if env.prefix provided) and command-line flags.

func ParseFlagSet

func ParseFlagSet(fs *flag.FlagSet, args []string)

ParseFlagSet parses the given args into the given fs.

func PositiveDurationValue

func PositiveDurationValue(s string, step int64) (int64, error)

PositiveDurationValue returns positive duration in milliseconds for the given s and the given step.

Duration in s may be combined, i.e. 2h5m or 2h-5m.

Error is returned if the duration in s is negative.

func RegisterSecretFlag

func RegisterSecretFlag(flagName string)

RegisterSecretFlag registers flagName as secret.

This function must be called before starting logging. It cannot be called from concurrent goroutines.

Secret flags aren't exported at `/metrics` page.

func Usage

func Usage(s string)

Usage prints s and optional description for all the flags if -h or -help flag is passed to the app.

func Visit

func Visit(fn func(string, string))

Visit the flags name and values set in command line

func VisitAll

func VisitAll(fn func(string, string))

Visit all the flag name and values, including those not set in command line.

func WriteFlags

func WriteFlags(w io.Writer)

WriteFlags writes all the explicitly set flags to w.

Types

type ArrayBool

type ArrayBool []bool

ArrayBool is a flag that holds an array of booleans values.

Has the same api as ArrayString.

func NewArrayBool

func NewArrayBool(name, usage string, opts ...Option) *ArrayBool

NewArrayBool returns new ArrayBool with the given name and description.

func (*ArrayBool) GetOptionalArg

func (a *ArrayBool) GetOptionalArg(argIdx int) bool

GetOptionalArg returns optional arg under the given argIdx.

func (*ArrayBool) IsBoolFlag

func (a *ArrayBool) IsBoolFlag() bool

IsBoolFlag implements flag.IsBoolFlag interface

func (*ArrayBool) Set

func (a *ArrayBool) Set(value string) error

Set implements flag.Value interface

func (*ArrayBool) String

func (a *ArrayBool) String() string

String implements flag.Value interface

type ArrayBytes

type ArrayBytes []*Bytes

ArrayBytes is flag that holds an array of Bytes.

Has the same api as ArrayString.

func NewArrayBytes

func NewArrayBytes(name, usage string, opts ...Option) *ArrayBytes

NewArrayBytes returns new ArrayBytes with the given name and description.

func (*ArrayBytes) GetOptionalArgOrDefault

func (a *ArrayBytes) GetOptionalArgOrDefault(argIdx int, defaultValue int64) int64

GetOptionalArgOrDefault returns optional arg under the given argIdx.

func (*ArrayBytes) Ints

func (a *ArrayBytes) Ints() []int

func (*ArrayBytes) Set

func (a *ArrayBytes) Set(value string) error

Set implemented flag.Value interface

func (*ArrayBytes) String

func (a *ArrayBytes) String() string

String implements flag.Value interface

type ArrayDuration

type ArrayDuration []time.Duration

ArrayDuration is a flag that holds an array of time.Duration values.

Has the same api as ArrayString.

func NewArrayDuration

func NewArrayDuration(name, usage string, opts ...Option) *ArrayDuration

NewArrayDuration returns new ArrayDuration with the given name and description.

func (*ArrayDuration) GetOptionalArgOrDefault

func (a *ArrayDuration) GetOptionalArgOrDefault(argIdx int, defaultValue time.Duration) time.Duration

GetOptionalArgOrDefault returns optional arg under the given argIdx, or default value, if argIdx not found.

func (*ArrayDuration) Set

func (a *ArrayDuration) Set(value string) error

Set implements flag.Value interface

func (*ArrayDuration) String

func (a *ArrayDuration) String() string

String implements flag.Value interface

type ArrayInt

type ArrayInt []int

ArrayInt is flag that holds an array of ints.

Has the same api as ArrayString.

func NewArrayInt

func NewArrayInt(name, usage string, opts ...Option) *ArrayInt

NewArrayInt returns new ArrayInt with the given name and description.

func (*ArrayInt) GetOptionalArgOrDefault

func (a *ArrayInt) GetOptionalArgOrDefault(argIdx, defaultValue int) int

GetOptionalArgOrDefault returns optional arg under the given argIdx.

func (*ArrayInt) Set

func (a *ArrayInt) Set(value string) error

Set implements flag.Value interface

func (*ArrayInt) String

func (a *ArrayInt) String() string

String implements flag.Value interface

type ArrayString

type ArrayString []string

ArrayString is a flag that holds an array of strings.

It may be set either by specifying multiple flags with the given name passed to NewArray or by joining flag values by comma.

The following example sets equivalent flag array with two items (value1, value2):

-foo=value1 -foo=value2
-foo=value1,value2

Each flag value may contain commas inside single quotes, double quotes, [], () or {} braces. For example, -foo=[a,b,c] defines a single command-line flag with `[a,b,c]` value.

Flag values may be quoted. For instance, the following arg creates an array of ("a", "b,c") items:

-foo='a,"b,c"'

func NewArrayString

func NewArrayString(name, usage string, opts ...Option) *ArrayString

NewArrayString returns new ArrayString with the given name and description.

func (*ArrayString) GetOptionalArg

func (a *ArrayString) GetOptionalArg(argIdx int) string

GetOptionalArg returns optional arg under the given argIdx.

func (*ArrayString) Set

func (a *ArrayString) Set(value string) error

Set implements flag.Value interface

func (*ArrayString) String

func (a *ArrayString) String() string

String implements flag.Value interface

type ArrayText

type ArrayText []*Text

ArrayText is a flag that used to hold multiple Text values.

func NewArrayText

func NewArrayText(name, usage string, opts ...Option) *ArrayText

NewArrayBytes returns new ArrayText with the given name and description.

func (*ArrayText) Set

func (a *ArrayText) Set(value string) error

Set implements flag.Value interface

func (*ArrayText) String

func (a *ArrayText) String() string

String implements flag.Value interface

func (*ArrayText) Strings

func (a *ArrayText) Strings() []string

type Bytes

type Bytes struct {
	// N contains parsed value for the given flag.
	N int64
	// contains filtered or unexported fields
}

Bytes is a flag for holding size in bytes.

It supports the following optional suffixes for values: KB, MB, GB, TB, KiB, MiB, GiB, TiB.

func NewBytes

func NewBytes(name string, defaultValue int64, usage string, opts ...Option) *Bytes

NewBytes returns new `bytes` flag with the given name, defaultValue and description.

func (*Bytes) IntN

func (b *Bytes) IntN() int

IntN returns the stored value capped by int type.

func (*Bytes) Set

func (b *Bytes) Set(value string) error

Set implements flag.Value interface

func (*Bytes) String

func (b *Bytes) String() string

String implements flag.Value interface

type Duration

type Duration struct {
	// Msecs contains parsed duration in milliseconds.
	Msecs int64
	// contains filtered or unexported fields
}

Duration is a flag for holding duration.

func NewDuration

func NewDuration(name string, defaultValue string, usage string, opts ...Option) *Duration

NewDuration returns new `duration` flag with the given name, defaultValue and description.

DefaultValue is in months.

func (*Duration) Set

func (d *Duration) Set(value string) error

Set implements flag.Value interface

func (*Duration) String

func (d *Duration) String() string

String implements flag.Value interface

type Option

type Option func(*option)

Option for flags

func AfterParse added in v0.3.0

func AfterParse(f func(isSet bool, set func(string) error)) Option

AfterParse set a function to be called after parsing flags. The function must not block.

func Env

func Env(env string) Option

Env customize environment for flag.

func Required

func Required() Option

Required mark the flag MUST BE set via command line or environment

type Text

type Text struct {
	Value string
}

Text is a flag that used to hold complex content, such as json. the passed value should be base64-encoded string, it will be decoded before assignment.

func NewText

func NewText(name string, value string, usage string, opts ...Option) *Text

NewText creates a new text flag.

func (*Text) MarshalText

func (t *Text) MarshalText() ([]byte, error)

func (*Text) UnmarshalText

func (t *Text) UnmarshalText(text []byte) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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