Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse strings like command line arguments with Go

How do I take a string and parse it as if it was a series of command line arguments? I want to be able to take a string and parse that with flag and/or pflag. How do I do this?

package main

import (
    "fmt"
    "os"

    flag "github.com/spf13/pflag"
)

func main() {
    command := `unimportant -fb "quoted string"`
    var (
        foo bool
        bar string
    )
    flag.BoolVarP(&foo, "foo", "f", false, "foo")
    flag.StringVarP(&bar, "bar", "b", "default", "bar")

    // Parse command
    os.Args = append(os.Args, "-fb", "quoted string")
    flag.Parse()

    fmt.Println(command)
    fmt.Println("foo", foo)
    fmt.Println("bar", bar)
}
like image 677
pythonian 23 Avatar asked Apr 19 '26 12:04

pythonian 23


1 Answers

The easiest way would be use the package shellwords to parse your string into an argv of shell words, and then use a command-line parser other than flag or pflag that supports parsing an arbitrary argv (say flags, but there are many to choose from.)

// Parse  your string into an []string as the shell would.

argv, err := shellwords.Parse("./foo --bar=baz")
// argv should be ["./foo", "--bar=baz"]

...

// define your options, etc. here

...

extraArgs, err := flags.ParseArgs(&opts, argv)
like image 69
Nicholas Carey Avatar answered Apr 21 '26 07:04

Nicholas Carey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!