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

如何在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

我希望来自控制台的输入具有匿名参数。 我当前的执行方式是 p>

./ app -infc = eth0 -ip = 192.168.0.1 p> blockquote>

我不想要这个 需要此应用程序具有通用性,以便我也可以将其用于其他目的。 p>

我希望CLI像这样 strong> p>

./ app -firstparam = {{infc},eth0} -secondparam = {{ip},192.168.0.1} p> blockquote> 因此,这基本上应该通过读取参数中的两列来实现。 p>

因此,它应该将参数解析为内部键值对 p>

需要有关如何将每个参数存储为键值对以及以后分别使用它们的帮助 p> div>

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())
}

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]
}