golang自动从结构体字段定义命令行标志插件库autoflags的使用
golang自动从结构体字段定义命令行标志插件库autoflags的使用
autoflags包提供了一种便捷的方式,可以将结构体字段暴露为命令行标志。需要暴露的字段应该附加flag
标签:flag:"flagName,usage string"
。
完整示例demo
下面是一个使用autoflags的完整示例:
package main
import (
"fmt"
"log"
"github.com/artyom/autoflags"
)
// Config 结构体定义了命令行参数
type Config struct {
Host string `flag:"host,server host"` // 服务器主机地址
Port int `flag:"port,server port"` // 服务器端口号
Debug bool `flag:"debug,enable debug mode"` // 是否启用调试模式
Timeout int `flag:"timeout,request timeout in seconds"` // 请求超时时间(秒)
Rate float64 `flag:"rate,request rate limit"` // 请求速率限制
}
func main() {
// 创建配置实例
cfg := &Config{
Host: "localhost", // 默认主机
Port: 8080, // 默认端口
Timeout: 30, // 默认超时时间
Rate: 1.0, // 默认速率限制
}
// 自动解析命令行参数到结构体
if err := autoflags.Parse(cfg); err != nil {
log.Fatal(err)
}
// 打印配置信息
fmt.Printf("Server: %s:%d\n", cfg.Host, cfg.Port)
fmt.Printf("Debug mode: %v\n", cfg.Debug)
fmt.Printf("Timeout: %d seconds\n", cfg.Timeout)
fmt.Printf("Rate limit: %.2f\n", cfg.Rate)
}
使用说明
- 定义结构体时,为需要作为命令行参数的字段添加
flag
标签 - 标签格式为:
flag:"名称,使用说明"
- 调用
autoflags.Parse()
方法自动解析命令行参数到结构体
运行示例
编译并运行程序时可以指定各种参数:
# 使用默认值运行
$ ./example
# 指定自定义参数运行
$ ./example -host example.com -port 9000 -debug -timeout 60 -rate 2.5
支持的字段类型
autoflags支持以下类型的结构体字段:
- string
- int, int8, int16, int32, int64
- uint, uint8, uint16, uint32, uint64
- float32, float64
- bool
- time.Duration
这个库简化了命令行参数的解析过程,特别适合需要大量命令行参数的应用程序。
更多关于golang自动从结构体字段定义命令行标志插件库autoflags的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于golang自动从结构体字段定义命令行标志插件库autoflags的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
Golang 自动从结构体生成命令行标志 - autoflags 使用指南
autoflags
是一个方便的 Go 库,它可以从结构体定义自动生成命令行标志(flags),简化命令行程序的开发。下面我将详细介绍如何使用它。
安装
go get github.com/artyom/autoflags
基本用法
package main
import (
"fmt"
"log"
"github.com/artyom/autoflags"
)
type Config struct {
Host string `flag:"host" desc:"server host"`
Port int `flag:"port" desc:"server port"`
Debug bool `flag:"debug" desc:"enable debug mode"`
Timeout int `flag:"timeout" desc:"connection timeout in seconds"`
MaxConns int `flag:"max-conns" desc:"maximum connections"`
}
func main() {
cfg := Config{
Host: "localhost",
Port: 8080,
Timeout: 30,
MaxConns: 100,
}
// 自动解析命令行参数到结构体
if err := autoflags.Parse(&cfg); err != nil {
log.Fatal(err)
}
fmt.Printf("Running server on %s:%d (debug=%v)\n", cfg.Host, cfg.Port, cfg.Debug)
fmt.Printf("Timeout: %ds, Max connections: %d\n", cfg.Timeout, cfg.MaxConns)
}
特性说明
- 自动生成标志:根据结构体字段自动生成对应的命令行标志
- 类型支持:支持基本类型(string, int, bool等)和time.Duration
- 标签控制:
flag:"name"
- 指定标志名称desc:"description"
- 指定帮助信息default:"value"
- 指定默认值(可选)
高级用法
嵌套结构体
type DatabaseConfig struct {
DSN string `flag:"dsn" desc:"database connection string"`
PoolSize int `flag:"pool-size" desc:"connection pool size"`
}
type AppConfig struct {
Server struct {
Host string `flag:"host" desc:"server host"`
Port int `flag:"port" desc:"server port"`
}
DB DatabaseConfig
}
func main() {
cfg := AppConfig{
Server: struct {
Host string
Port int
}{
Host: "localhost",
Port: 8080,
},
DB: DatabaseConfig{
DSN: "user:pass@/dbname",
PoolSize: 10,
},
}
if err := autoflags.Parse(&cfg); err != nil {
log.Fatal(err)
}
}
自定义帮助信息
func main() {
cfg := Config{
Host: "localhost",
Port: 8080,
}
// 在解析前可以修改flag.Usage
autoflags.SetUsage("myapp", "A sample application", &cfg)
if err := autoflags.Parse(&cfg); err != nil {
log.Fatal(err)
}
}
必填参数
type Config struct {
APIKey string `flag:"api-key" desc:"API key (required)" required:"true"`
}
与其他库的比较
- 标准库flag:需要手动定义每个标志,代码冗长
- pflag:功能更强大但需要手动定义
- autoflags:自动从结构体生成,减少样板代码
注意事项
- 结构体字段必须是导出的(大写字母开头)
- 不支持切片类型(除非使用
github.com/artyom/sliceflags
扩展) - 默认值由结构体实例的初始值决定
完整示例
package main
import (
"fmt"
"log"
"time"
"github.com/artyom/autoflags"
)
type Config struct {
Address string `flag:"address" desc:"server address"`
Port int `flag:"port" desc:"server port"`
Debug bool `flag:"debug" desc:"enable debug mode"`
Timeout time.Duration `flag:"timeout" desc:"connection timeout"`
Concurrency int `flag:"concurrency" desc:"max concurrent requests"`
ConfigFile string `flag:"config" desc:"config file path"`
}
func main() {
cfg := Config{
Address: "0.0.0.0",
Port: 8080,
Timeout: 30 * time.Second,
Concurrency: 100,
}
autoflags.SetUsage("myapp", "A sample HTTP server", &cfg)
if err := autoflags.Parse(&cfg); err != nil {
log.Fatal(err)
}
fmt.Printf("Starting server on %s:%d\n", cfg.Address, cfg.Port)
fmt.Printf("Timeout: %v, Concurrency: %d\n", cfg.Timeout, cfg.Concurrency)
if cfg.Debug {
fmt.Println("Debug mode enabled")
}
if cfg.ConfigFile != "" {
fmt.Printf("Using config file: %s\n", cfg.ConfigFile)
}
}
使用方式:
go run main.go --address=127.0.0.1 --port=9000 --debug --timeout=1m
autoflags
通过结构体标签和反射自动生成命令行接口,可以显著减少编写命令行程序时的样板代码,特别适合配置项较多的应用程序。