go解析命令行的3种方式

方式1:只用参数值

package main

import (
	"fmt"
	"os"
)

func main() {
	// os.Args是[]string
	for k, v := range os.Args {
		fmt.Printf("args[%d]=[%s]\n", k, v)
	}
}

方式2:flag参数+参数值

package main

import (
	"flag"
	"fmt"
)

func main() {
	var username string
	var password string

	flag.StringVar(&username, "u", "", "username")
	flag.StringVar(&password, "p", "", "password")
	flag.Parse()

	fmt.Printf("username=%s password=%s\n", username, password)
}

方式3:cobra参数+参数值

go get github.com/spf13/cobra@latest
package main

import (
	"fmt"

	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	Use:   "test",
	Short: "",
	Long:  ``,
	Run:   func(cmd *cobra.Command, args []string) {},
}

func main() {
	var username string
	var password string

	var testCmd = &cobra.Command{
		Use:   "test",
		Short: "--u username --p password",
		Long:  ``,
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Printf("username is %s, password is %s\n", username, password)
		},
	}

	rootCmd.AddCommand(testCmd)
	testCmd.Flags().StringVar(&username, "u", "", "username")
	testCmd.Flags().StringVar(&password, "p", "", "password")

	rootCmd.Execute()
}

posted on 2024-07-05 07:15  王景迁  阅读(11)  评论(0编辑  收藏  举报

导航