คู่มือฉบับเต็มในการสร้างเครื่องมือบรรทัดคำสั่ง (Command-Line Interface) ด้วย Cobra และ Viper อย่างมืออาชีพ
บทนำ
การสร้าง CLI Tools ด้วยภาษา Go ได้รับความนิยมสูงในหมู่นักพัฒนา เนื่องจาก Go สร้าง binary ที่รันเร็ว ขนาดเล็ก และพกพาง่าย ในบทความนี้เราจะพาคุณไปเรียนรู้วิธีใช้ Cobra สำหรับการจัดการคำสั่ง และ Viper สำหรับจัดการ configuration อย่างยืดหยุ่น
คุณจะสามารถสร้าง CLI ที่รองรับ:
- Subcommand
- Flags
- Config จากไฟล์ .yaml, .env หรือ environment variable
ติดตั้ง Cobra และ Viper
go get -u github.com/spf13/cobra@latest go get -u github.com/spf13/viper@latest
สร้างโครงสร้างโปรเจกต์ CLI
go mod init mycli mkdir cmd touch main.go
เริ่มต้นด้วย Cobra
main.go
package main import "mycli/cmd" func main() { cmd.Execute() }
cmd/root.go
package cmd import ( "fmt" "github.com/spf13/cobra" ) var rootCmd = &cobra.Command{ Use: "mycli", Short: "A CLI tool built with Cobra", Run: func(cmd *cobra.Command, args []string) { fmt.Println("Welcome to mycli!") }, } func Execute() { cobra.CheckErr(rootCmd.Execute()) }
เพิ่ม Subcommand
cmd/hello.go
package cmd import ( "fmt" "github.com/spf13/cobra" ) var name string var helloCmd = &cobra.Command{ Use: "hello", Short: "Say Hello", Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Hello, %s!\n", name) }, } func init() { helloCmd.Flags().StringVarP(&name, "name", "n", "world", "Your name") rootCmd.AddCommand(helloCmd) }
เรียกใช้แบบ:
mycli hello --name=King
ใช้ Viper สำหรับ config
สร้างไฟล์ config.yaml
appname: mycli author: King Pool debug: true
cmd/config.go
package cmd import ( "fmt" "github.com/spf13/viper" "github.com/spf13/cobra" ) var configCmd = &cobra.Command{ Use: "config", Run: func(cmd *cobra.Command, args []string) { fmt.Println("Author:", viper.GetString("author")) fmt.Println("Debug mode:", viper.GetBool("debug")) }, } func init() { rootCmd.AddCommand(configCmd) viper.SetConfigName("config") viper.SetConfigType("yaml") viper.AddConfigPath(".") viper.AutomaticEnv() if err := viper.ReadInConfig(); err != nil { fmt.Println("No config file found") } }
เรียกใช้แบบ:
mycli config
รองรับ Environment Variables
viper.BindEnv("debug") debug := viper.GetBool("debug")
ตั้งค่าผ่าน shell:
export DEBUG=true
รองรับ Config จาก Flag → Env → Config File
viper.BindPFlag("debug", rootCmd.PersistentFlags().Lookup("debug")) viper.BindEnv("debug") viper.SetDefault("debug", false)
ลำดับ Priority:
- Flag
- Env
- Config file
- Default
โครงสร้างโปรเจกต์สุดท้าย
mycli/ ├── cmd/ │ ├── config.go │ ├── hello.go │ └── root.go ├── config.yaml ├── go.mod └── main.go
ประโยชน์ของ Cobra + Viper
- CLI ที่มีโครงสร้างชัดเจน
- รองรับ command hierarchy
- ใช้ config แบบ flexible ได้หลายแหล่ง
- รองรับ autocomplete, help, usage message
คำค้น (SEO Keywords)
- Go CLI Tools
- Cobra Go
- Viper Go
- Command Line Tool ด้วย Go
- Config .yaml Go
- Build CLI App Go
- Go Subcommand CLI