Golang 命令行(CMD)开发指南
1. 标准库 flag 包基础用法
package main
import (
"flag"
"fmt"
)
func main() {
// 定义命令行参数
var (
host = flag.String("host", "localhost", "Server host")
port = flag.Int("port", 8080, "Server port")
debug = flag.Bool("debug", false, "Enable debug mode")
username string
)
// 自定义变量绑定
flag.StringVar(&username, "user", "", "Username for authentication")
// 解析参数
flag.Parse()
fmt.Printf("Starting server at %s:%d (debug=%t)\n", *host, *port, *debug)
if username != "" {
fmt.Println("Authenticated user:", username)
}
}
使用方式:
$ go run main.go -host=0.0.0.0 -port=9000 -user=admin -debug=true
2. Cobra - 专业级CLI框架
安装:
go get github.com/spf13/cobra@latest
基本项目结构:
myapp/
├── cmd/
│ ├── root.go # 根命令
│ ├── serve.go # serve子命令
│ └── version.go # version子命令
└── main.go # 程序入口
root.go示例:
package cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "MyApp is a demo CLI application",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your application`,
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
serve子命令示例:
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var (
serveHost string
servePort int
)
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Start the server",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Starting server on %s:%d\n", serveHost, servePort)
// 实际服务启动代码...
},
}
func init() {
rootCmd.AddCommand(serveCmd)
// Flags配置
serveCmd.Flags().StringVarP(&serveHost,
"host", "", "localhost",
"Server host address")
serveCmd.Flags().IntVarP(&servePort,
"port", "p", 8080,
"Server port number")
}
3. Viper集成配置管理
结合Cobra实现配置加载:
import (
"github.com/spf13/viper"
)
func initConfig() {
// Config文件自动搜索路径 (./config.yaml等)
viper.AutomaticEnv()
if cfgFile != "" { // --config参数指定的配置文件路径
viper.SetConfigFile(cfgFile)
if err := viper.ReadInConfig(); err != nil {
fmt.Println("Can't read config:", err)
os.Exit(1)
}
fmt.Println("Using config file:", viper.ConfigFileUsed())
// Watch配置热更新 (可选)
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:", e.Name)
// Reload逻辑...
})
}
}
4. Go-Args高级特性库
对于复杂参数解析需求,推荐使用:
go get github.com/alexflint/go-arg@latest
示例:
package main
import (
"fmt"
"github.com/alexflint/go-arg"
)
type Args struct {
Name string `arg:"required"`
DockerTag string `arg:"env:DOCKER_TAG"`
structTags struct { ... } `arg:"subcommand"`
listen struct { ... } `arg:"subcommand"`
}
func main() {
var args Args
p := arg.MustParse(&args)
if p.Subcommand() == nil {
p.Fail("missing subcommand")
return
}
switch p.Subcommand().Name() { ... }
}
需要我针对某个具体场景提供更详细的实现方案吗?
内容由零声教学AI助手提供,问题来源于学员提问