flags

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2025 License: BSD-3-Clause Imports: 11 Imported by: 0

README

flags

flags提供了一种命令行参数解析方式。该库设计灵感来源于标准库net/http以及一些三方框架,如echo。该库将命令行参数分为两种:命令和参数。

  • 命令:不带-开头的参数;
  • 参数:以-开头的参数。

示例:

your_app_name draw --shape circle
  • your_app_name:应用名称;
  • draw:命令名称;
  • --shape:参数,参数值为"circle"。

Features

支持参数类型(u)int(8|16|32|64)float(32|64)stringbooltime.Durationtime.Time,以及有限的mapslice

中间件:可以像http中间件一样,自定义中间件,在命令前后执行特定逻辑。

状态空间:类似命名空间,为一些命令单独开辟一个状态空间,用于注册中间件等逻辑,不影响之后命令的中间件注册。

自动生成帮助文档:根据参数和命令注册顺序,自动生成对应文档,可以根据-h--help来查看。

用法

// test.go
package main

import (
	"context"
	"fmt"

	"codeberg.org/3w/flags"
)

func main() {
	fs := flags.Cmdline("this is a test app desc")

	bar := fs.Cmd("bar", "the first sub command", func(ctx context.Context, handler flags.Handler) {
		fmt.Printf("before bar\n")
		handler(ctx)
		fmt.Printf("bar quit\n")
	})
	bar.Handle(func(context.Context) {
		fmt.Println("bar")
	})

	file := fs.Str('c', "config", "app.cfg", "config file")

	fs.Use(func(ctx context.Context, handler flags.Handler) {
		fmt.Printf("config file: %v\n", *file)
		handler(ctx)
		fmt.Println("main quit")
	})

	fs.Handle(func(context.Context) {
		fmt.Println("handler")
	})

	foo := fs.Cmd("foo", "the second sub command", func(ctx context.Context, handler flags.Handler) {
		fmt.Printf("before foo, config file: %v\n", *file)
		handler(ctx)
		fmt.Printf("foo quit\n")
	})
	foo.Handle(func(context.Context) {
		fmt.Println("foo")
	})

	fs.RunCmdline(context.Background())
}

执行go run test.go -h

$ go run test.go -h
test - this is a test app desc

Usage:
  test [option|command]

Options:
  -c, --config string (default: "app.cfg")
    config file

Commands:
  bar
    the first sub command

  foo
    the second sub command

执行go run test.go

$ go run test.go
config file: app.cfg
handler
quit

执行go run test.go bar -h

$ go run test.go bar -h
test bar - the first sub command

Usage:
  test bar

执行go run test.go bar

before bar
bar
bar quit

执行go run test.go foo -h

$ go run test.go foo -h
test foo - a sub command

Usage:
  test foo [option]

Options:
  -c, --config string (default: "app.cfg")
    config file

执行go run test.go foo

config file: app.cfg
before foo, config file: app.cfg
foo
foo quit
main quit

执行go run test.go bar -c app.cfg

$ go run test.go bar -c config
bar: unknown option: -c

执行go run test.go -c app.cfg bar(参数-c无效):

$ go run test.go -c app.cfg bar
before bar
bar
bar quit

执行go run test.go -c app.cfg foo -c app.json-c参数值以最后一个为准):

$ go run test.go -c app.cfg foo -c app.json
config file: app.json
before foo, config file: app.json
foo
foo quit
main quit

Documentation

Index

Constants

View Source
const (
	NoShort byte   = 0  // 不设置短参数
	NoLong  string = "" // 不设置长参数
)
View Source
const DateTime = "2006-01-02T15:04:05"

时间参数格式

Variables

View Source
var (
	ErrNoExecFunc   = errors.New("no exec func")
	ErrNoInputValue = errors.New("no input value")
	ErrHelp         = errors.New("help")
)

Functions

func Any

func Any[T Types[K, V], K KeyTypes, V ElemTypes](fs *FlagSet, short byte, long string, dft T, desc string, opts ...Options) *T

func AnyVar

func AnyVar[T Types[K, V], K KeyTypes, V ElemTypes](fs *FlagSet, ptr *T, short byte, long string, dft T, desc string, opts ...Options)

func CurrentCommandUsage

func CurrentCommandUsage(ctx context.Context) string

CurrentCommandUsage:当前命令用法

func Map

func Map[K KeyTypes, V ElemTypes](fs *FlagSet, short byte, long string, dft map[K]V, desc string, opts ...Options) *map[K]V

func MapSlice

func MapSlice[K KeyTypes, V ElemTypes](fs *FlagSet, short byte, long string, dft map[K][]V, desc string, opts ...Options) *map[K][]V

func MapSliceVar

func MapSliceVar[K KeyTypes, V ElemTypes](fs *FlagSet, ptr *map[K][]V, short byte, long string, dft map[K][]V, desc string, opts ...Options)

func MapVar

func MapVar[K KeyTypes, V ElemTypes](fs *FlagSet, ptr *map[K]V, short byte, long string, dft map[K]V, desc string, opts ...Options)

func Slice

func Slice[T ElemTypes](fs *FlagSet, short byte, long string, dft []T, desc string, opts ...Options) *[]T

func SliceMap

func SliceMap[K KeyTypes, V ElemTypes](fs *FlagSet, short byte, long string, dft []map[K]V, desc string, opts ...Options) *[]map[K]V

func SliceMapVar

func SliceMapVar[K KeyTypes, V ElemTypes](fs *FlagSet, ptr *[]map[K]V, short byte, long string, dft []map[K]V, desc string, opts ...Options)

func SliceVar

func SliceVar[T ElemTypes](fs *FlagSet, ptr *[]T, short byte, long string, dft []T, desc string, opts ...Options)

func ValidLong

func ValidLong(long string) bool

func ValidShort

func ValidShort(short byte) bool

Types

type ComTypes

type ComTypes[K KeyTypes, V ElemTypes] interface {
	[]V | map[K]V | []map[K]V | map[K][]V
}

type ElemTypes

type ElemTypes interface {
	KeyTypes | time.Time
}

type FlagSet

type FlagSet struct {
	// contains filtered or unexported fields
}

FlagSet提供一组参数解析/命令执行的绑定关系。不可复用,如需要重复解析,需重新生成新的FlagSet。

func Cmdline

func Cmdline(desc string) *FlagSet

func New

func New(name, desc string) *FlagSet

New生成一次性解析对象。name:应用名称,desc:应用描述,用于生成usage

func (*FlagSet) AnyVar

func (fs *FlagSet) AnyVar(ptr any, short byte, long string, dft any, desc string, opts ...Options)

AnyVar: add any pointer to parse. param ptr must be a pointer, param dft should be nil if no default value, or else dft type must be reflect.TypeOf(ptr).Elem().

func (*FlagSet) Bool

func (fs *FlagSet) Bool(short byte, long string, dft bool, desc string, opts ...Options) *bool

func (*FlagSet) BoolVar

func (fs *FlagSet) BoolVar(ptr *bool, short byte, long string, dft bool, desc string, opts ...Options)

func (*FlagSet) Cmd

func (fs *FlagSet) Cmd(name, desc string, mws ...Middleware) *FlagSet

Cmd:注册子命令,及子命令用到的中间件。

func (*FlagSet) DateTime

func (fs *FlagSet) DateTime(short byte, long string, dft time.Time, desc string, opts ...Options) *time.Time

func (*FlagSet) DateTimeVar

func (fs *FlagSet) DateTimeVar(ptr *time.Time, short byte, long string, dft time.Time, desc string, opts ...Options)

func (*FlagSet) Duration

func (fs *FlagSet) Duration(short byte, long string, dft time.Duration, desc string, opts ...Options) *time.Duration

func (*FlagSet) DurationVar

func (fs *FlagSet) DurationVar(ptr *time.Duration, short byte, long string, dft time.Duration, desc string, opts ...Options)

func (*FlagSet) Float32

func (fs *FlagSet) Float32(short byte, long string, dft float32, desc string, opts ...Options) *float32

func (*FlagSet) Float32Var

func (fs *FlagSet) Float32Var(ptr *float32, short byte, long string, dft float32, desc string, opts ...Options)

func (*FlagSet) Float64

func (fs *FlagSet) Float64(short byte, long string, dft float64, desc string, opts ...Options) *float64

func (*FlagSet) Float64Var

func (fs *FlagSet) Float64Var(ptr *float64, short byte, long string, dft float64, desc string, opts ...Options)

func (*FlagSet) Handle

func (fs *FlagSet) Handle(h Handler, mws ...Middleware)

Handle:设置Handler,并可以同时设置该handler的中间件

func (*FlagSet) Int

func (fs *FlagSet) Int(short byte, long string, dft int, desc string, opts ...Options) *int

func (*FlagSet) Int16

func (fs *FlagSet) Int16(short byte, long string, dft int16, desc string, opts ...Options) *int16

func (*FlagSet) Int16Var

func (fs *FlagSet) Int16Var(ptr *int16, short byte, long string, dft int16, desc string, opts ...Options)

func (*FlagSet) Int32

func (fs *FlagSet) Int32(short byte, long string, dft int32, desc string, opts ...Options) *int32

func (*FlagSet) Int32Var

func (fs *FlagSet) Int32Var(ptr *int32, short byte, long string, dft int32, desc string, opts ...Options)

func (*FlagSet) Int64

func (fs *FlagSet) Int64(short byte, long string, dft int64, desc string, opts ...Options) *int64

func (*FlagSet) Int64Var

func (fs *FlagSet) Int64Var(ptr *int64, short byte, long string, dft int64, desc string, opts ...Options)

func (*FlagSet) Int8

func (fs *FlagSet) Int8(short byte, long string, dft int8, desc string, opts ...Options) *int8

func (*FlagSet) Int8Var

func (fs *FlagSet) Int8Var(ptr *int8, short byte, long string, dft int8, desc string, opts ...Options)

func (*FlagSet) IntVar

func (fs *FlagSet) IntVar(ptr *int, short byte, long string, dft int, desc string, opts ...Options)

func (*FlagSet) Parsed

func (fs *FlagSet) Parsed(pointer any) bool

func (*FlagSet) Run

func (fs *FlagSet) Run(ctx context.Context, args ...string) (string, error)

Run:解析参数,并调用子命令handler。常见用法为:`fs.Run(context.Background(), os.Args[1:]...)`。 返回Usage及错误信息。Usage保持不为空,业务可根据需要判断是否需要展示Usage。

func (*FlagSet) RunCmdline

func (fs *FlagSet) RunCmdline(ctx context.Context)

func (*FlagSet) Stmt

func (fs *FlagSet) Stmt(mws ...Middleware) *FlagSet

Stmt:开启一个单独的状态,可用于注册特定中间件,不影响Stmt之后的命令。

func (*FlagSet) Str

func (fs *FlagSet) Str(short byte, long string, dft string, desc string, opts ...Options) *string

func (*FlagSet) StrVar

func (fs *FlagSet) StrVar(ptr *string, short byte, long string, dft string, desc string, opts ...Options)

func (*FlagSet) Uint

func (fs *FlagSet) Uint(short byte, long string, dft uint, desc string, opts ...Options) *uint

func (*FlagSet) Uint16

func (fs *FlagSet) Uint16(short byte, long string, dft uint16, desc string, opts ...Options) *uint16

func (*FlagSet) Uint16Var

func (fs *FlagSet) Uint16Var(ptr *uint16, short byte, long string, dft uint16, desc string, opts ...Options)

func (*FlagSet) Uint32

func (fs *FlagSet) Uint32(short byte, long string, dft uint32, desc string, opts ...Options) *uint32

func (*FlagSet) Uint32Var

func (fs *FlagSet) Uint32Var(ptr *uint32, short byte, long string, dft uint32, desc string, opts ...Options)

func (*FlagSet) Uint64

func (fs *FlagSet) Uint64(short byte, long string, dft uint64, desc string, opts ...Options) *uint64

func (*FlagSet) Uint64Var

func (fs *FlagSet) Uint64Var(ptr *uint64, short byte, long string, dft uint64, desc string, opts ...Options)

func (*FlagSet) Uint8

func (fs *FlagSet) Uint8(short byte, long string, dft uint8, desc string, opts ...Options) *uint8

func (*FlagSet) Uint8Var

func (fs *FlagSet) Uint8Var(ptr *uint8, short byte, long string, dft uint8, desc string, opts ...Options)

func (*FlagSet) UintVar

func (fs *FlagSet) UintVar(ptr *uint, short byte, long string, dft uint, desc string, opts ...Options)

func (*FlagSet) Usage

func (fs *FlagSet) Usage() string

Usage:生成help信息。

func (*FlagSet) Use

func (fs *FlagSet) Use(mws ...Middleware) *FlagSet

Use:设置中间件,所有以后注册的Handler会用到该中间件

type Handler

type Handler func(context.Context) // Handler: command handler,执行命令函数

type KeyTypes

type KeyTypes interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
		~float32 | ~float64 |
		~bool |
		~string
}

type Middleware

type Middleware func(ctx context.Context, handler Handler)

type Options

type Options interface {
	// contains filtered or unexported methods
}

Options:设置参数规则。 可选值有WithSliceSeperator、WithKeyValueSeperator、WithZeroDefault。

func WithKeyValueSeperator

func WithKeyValueSeperator(seperator string) Options

WithKeyValueSeperator:key/value切分规则,默认为":"。 应先设置WithSliceSeperator切分为kv对,再用kv seperator切分key/value值。

func WithSliceSeperator

func WithSliceSeperator(seperator string) Options

WithSliceSeperator:数组切分规则,默认为","。 用于map结构时,先以slice seperator切分成kv对,再用kv seperator切分key/value值。

func WithZeroDefault

func WithZeroDefault(zero bool) Options

WithZeroDefault:是否显示默认零值。 比如int参数为零值0时,将不在help中显示"(default: 0)"。 可设置该参数强制显示。

type Types

type Types[K KeyTypes, V ElemTypes] interface {
	ElemTypes | ComTypes[K, V]
}

Jump to

Keyboard shortcuts

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