How to parse a string array #1429
Answered
by
meatballhat
guptanitin280
asked this question in
Q&A
-
(warning: heavily edited by @meatballhat) I read through the doc but could not find how to parse argument like:
so when I use context.Args().Get(0) I get and when I use context.Args().Get(1) I get |
Beta Was this translation helpful? Give feedback.
Answered by
meatballhat
Jun 25, 2022
Replies: 1 comment
-
@guptanitin280 If your intent is for The primary intended use of For example: package main
import (
"encoding/json"
"fmt"
"log"
"os"
"github.com/urfave/cli/v2"
)
func main() {
sentenceFlag := &cli.StringSliceFlag{Name: "sentence"}
wordFlag := &cli.StringFlag{Name: "word"}
app := &cli.App{
Action: func(cCtx *cli.Context) error {
jb, err := json.MarshalIndent(map[string]interface{}{
"Args": cCtx.Args(),
"sentenceFlag": sentenceFlag.Get(cCtx),
"wordFlag": wordFlag.Get(cCtx),
}, "", " ")
if err != nil {
return err
}
fmt.Println(string(jb))
return nil
},
Flags: []cli.Flag{sentenceFlag, wordFlag},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
} $ go run example.go --word ok --sentence "hello,world" '["hello", "world"]' "Golang"
{
"Args": [
"[\"hello\", \"world\"]",
"Golang"
],
"sentenceFlag": [
"hello",
"world"
],
"wordFlag": "ok"
} $ go run example.go --word 'hello world' --sentence "hello" --sentence "world" '["hello", "world"]' "Golang"
{
"Args": [
"[\"hello\", \"world\"]",
"Golang"
],
"sentenceFlag": [
"hello",
"world"
],
"wordFlag": "hello world"
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
meatballhat
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@guptanitin280 If your intent is for
["hello", "world"]
to be parsed as a[]string{}
, thencli.Context.Args
is probably not what you want.The primary intended use of
cli.Context.Args
is to allow arbitrary positional arguments to be passed through (un-parsed!) to a given action.For example: