golang flag包使用总结

最近看NSQD源码使用flag+ toml配置文件的用法, 详细总结下.

flag

该包提供了一系列解析命令行参数的功能接口

toml

一个第三方的配置文件解析的包地址:http://github.com/BurntSushi/toml

example

一个小demo, 包括了, 覆盖了flag包大部分使用场景

package main

import (
    "flag"
    "fmt"
    "github.com/BurntSushi/toml"
    "github.com/mreiferson/go-options"
    "log"
    "math/rand"
    "os"
    "strings"
    "time"
)

func main() {
    // 设置conf 的默认值
    opts := newConf()
    flagSet := newOpts(opts)
    // 从命令行获取参数值
    flagSet.Parse(os.Args[1:])
    rand.Seed(time.Now().UTC().UnixNano())
    if flagSet.Lookup("version").Value.(flag.Getter).Get().(bool) {
        fmt.Println("Zsh-1.0.1")
        os.Exit(0)
    }
    configFile := flagSet.Lookup("config").Value.String()
    var cfg config

    if configFile != "" {
        _, err := toml.DecodeFile(configFile, &cfg)
        if err != nil {
            panic(err.Error())
        }
    }
    // 校验配置有效性
    cfg.Validate()
    // options 这个包能中和命令行, 配置文件,和默认配置的优先级
    options.Resolve(opts, flagSet, cfg)

    fmt.Println(opts.Url, opts.ListenPort, opts.MysqlAddr)
}

type Conf struct {
    AppName    string
    Version    string
    MysqlAddr  string   `flag:"mysql"` // 这里的flag tag 是在参数行的key,和json tag 类似;
    ListenPort int      `flag:"port"`
    Url        []string `flag:"url"`
}

type config map[string]interface{}

//参数校验
func (c config) Validate() {
    if port, ok := c["port"]; ok {
        if _, ok = port.(int64); !ok {
            log.Fatal("port must be Int")
        }
    }
}

// 设置参数的默认值
func newConf() *Conf {
    return &Conf{
        AppName:    "Zsh",
        ListenPort: 9090,
        Url:        StringArray{"127.0.0.1:2371"},
    }
}

func newOpts(c *Conf) *flag.FlagSet {
    // new 一个flagSet, 并且把默认的配置传进来.
    flagSet := flag.NewFlagSet("Zsh", flag.ExitOnError)
    flagSet.String("name", c.AppName, "应用名称, 默认Zsh")
    flagSet.String("v", "1.0.0.", "应用名字")
    flagSet.String("mysql", "127.0.0.1:3306", "mysql address.")
    flagSet.Int("port", c.ListenPort, "listen and port.")
    flagSet.String("config", "", "config path.")
    // 自定义类型, 这玩意我研究了半天!!
    url := StringArray{}
    flagSet.Var(&url, "url", "请求url")
    flagSet.Bool("version", false, "print version string")
    return flagSet
}

/*
要想在自定义类,必须实现Value, 和getter接口
type Value interface {
    String() string
    Set(string) error
}
type Getter interface {
    Value
    Get() interface{}
}

*/

type StringArray []string

func (a *StringArray) Get() interface{} { return []string(*a) }

func (a *StringArray) Set(s string) error {
    news := strings.Replace(s, " ", "", -1)
    *a = StringArray(strings.Split(news, ","))
    return nil
}

func (a *StringArray) String() string {
    return strings.Join(*a, ",")
}

你可能感兴趣的:(golang flag包使用总结)