donglu1881
donglu1881
2018-10-17 13:38

如何在Golang中借助标志使用随机参数

已采纳

I want the input from the console to be of anonymous parameters. My current way of execution is

./app -infc=eth0 -ip=192.168.0.1

I don't want this as I need this app to be universal so that I can use it for other purposes as well.

I want the CLI to be like this

./app -firstparam={{infc},eth0} -secondparam={{ip},192.168.0.1}

So this should basically work by reading the two columns in the parameters.

So it should parse the parameters as a an internal key value pair

Need help on how to store each of the parameter as a key value pair and later use them individually

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douqiao6015 douqiao6015 3年前

    Here's a barebones example to give you an idea how to process os.Args

    $ go run main.go --foo asdf --bar xxx --baz ccc
    map[--foo:asdf --bar:xxx --baz:ccc]
    jsandrew-Mac:osarg jsandrew$ cat main.go
    package main
    
    import (
        "fmt"
        "os"
    )
    
    func manyRandomArg() map[string]string {
        rv := make(map[string]string)
        for ix, x := range os.Args {
            if x[:2] == "--" {
                rv[x] = os.Args[ix+1]
            }
        }
        return rv
    }
    
    func main() {
        fmt.Printf("%v
    ", manyRandomArg())
    }
    
    点赞 评论 复制链接分享
  • duanping1920 duanping1920 3年前

    solved it thanks to @Vorsprung

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "log"
        "os"
        "regexp"
        "strings"
    )
    
    var key0, key1, key2, key3, key4, filename string
    var fileext = regexp.MustCompile(`([a-z]+)\.yaml`)
    
    func manyRandomArg() map[string]string {
        rv := make(map[string]string)
        for ix, x := range os.Args {
            if x[:2] == "--" {
                rv[x] = os.Args[ix+1]
            }
        }
        return rv
    }
    
    func main() {
        fmt.Printf("
    %v
    ", manyRandomArg())
        readargs()
    }
    func readargs() {
    
        rv := manyRandomArg()
        keys := make([]string, 0, len(rv))
        for key, _ := range rv {
            keys = append(keys, key)
        }
        // Convert map to slice of values.
        values := []string{}
        for _, value := range rv {
            values = append(values, value)
        }
    
        for keys, values := range rv {
            fmt.Printf("key[%s] value[%s]
    ", keys, values)
        }
        if fileext.MatchString(values[0]) {
            fmt.Printf("Value %s
    ", values[0])
            filename = values[0]
        } else if fileext.MatchString(values[1]) {
            fmt.Printf("Value %s
    ", values[1])
            filename = values[1]
        } else if fileext.MatchString(values[2]) {
            fmt.Printf("Value %s
    ", values[2])
            filename = values[2]
        } else if fileext.MatchString(values[3]) {
            fmt.Printf("Value %s
    ", values[3])
            filename = values[3]
        } else if fileext.MatchString(values[4]) {
            fmt.Printf("Value %s
    ", values[4])
            filename = values[4]
        } else {
            log.Fatal("index 4 fail")
            os.Exit(1)
        }
    
        b, err := ioutil.ReadFile(filename) // just pass the file name
        if err != nil {
            fmt.Print(err)
        }
        str := string(b) // convert content to a 'string'
        key0 = trimLeftChars(keys[0], 2)
        key1 = trimLeftChars(keys[1], 2)
        key2 = trimLeftChars(keys[2], 2)
        key3 = trimLeftChars(keys[3], 2)
        key4 = trimLeftChars(keys[4], 2)
    
        // Create replacer with pairs as arguments.
        r := strings.NewReplacer(key0, values[0], key1, values[1], key2, values[2], key3, values[3], key4, values[4])
    
        // Replace all pairs.
        result := r.Replace(str)
        fmt.Println(result)
    
        newContents := []byte(result)
        err = ioutil.WriteFile("new3.yaml", newContents, 0664)
        if err != nil {
            panic(err)
        }
    }
    func trimLeftChars(s string, n int) string {
        m := 0
        for i := range s {
            if m >= n {
                return s[i:]
            }
            m++
        }
        return s[:0]
    }
    
    点赞 评论 复制链接分享

为你推荐