From 14d114ec17869c0e46ddf3cf4ef06e38379ecf65 Mon Sep 17 00:00:00 2001 From: Ramana Reddy Date: Fri, 11 Aug 2023 22:28:14 +0530 Subject: [PATCH] add slice support to dynamic var --- dynamic_var.go | 14 ++++++++++++-- examples/basic/main.go | 3 +++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/dynamic_var.go b/dynamic_var.go index b5e69b2..ceff9b2 100644 --- a/dynamic_var.go +++ b/dynamic_var.go @@ -5,6 +5,7 @@ import ( "fmt" "reflect" "strconv" + "strings" ) type dynamicFlag struct { @@ -54,6 +55,13 @@ func (df *dynamicFlag) Set(value string) error { return nil } *stringField = value + case reflect.Slice: + sliceField := df.field.(*[]string) + if isBoolValue { + *sliceField = df.defaultValue.([]string) + return nil + } + *sliceField = append(*sliceField, strings.Split(value, ",")...) default: return errors.New("unsupported type") } @@ -70,8 +78,10 @@ func (df *dynamicFlag) String() string { // DynamicVar acts as flag with a default value or a option with value // example: -// var titleSize int -// flagSet.DynamicVar(&titleSize, "title", 50, "first N characters of the title") +// +// var titleSize int +// flagSet.DynamicVar(&titleSize, "title", 50, "first N characters of the title") +// // > go run ./examples/basic -title or go run ./examples/basic -title=100 // In case of `go run ./examples/basic -title` it will use default value 50 func (flagSet *FlagSet) DynamicVar(field interface{}, long string, defaultValue interface{}, usage string) *FlagData { diff --git a/examples/basic/main.go b/examples/basic/main.go index 2a10776..6f3f644 100644 --- a/examples/basic/main.go +++ b/examples/basic/main.go @@ -20,6 +20,7 @@ type Options struct { // Dynamic titleSize int target string + hashes []string } func main() { @@ -46,6 +47,7 @@ func main() { flagSet.CreateGroup("Dynmaic", "Dynamic", flagSet.DynamicVarP(&testOptions.titleSize, "title", "t", 50, "first N characters of the title"), flagSet.DynamicVarP(&testOptions.target, "target", "u", "https://example.com", "target url"), + flagSet.DynamicVarP(&testOptions.hashes, "hashes", "hs", []string{"md5", "sha1"}, "supported hashes"), ) flagSet.SetCustomHelpText("EXAMPLE USAGE:\ngo run ./examples/basic [OPTIONS]") @@ -56,6 +58,7 @@ func main() { // TODO: remove this fmt.Println("title size:", testOptions.titleSize) fmt.Println("target:", testOptions.target) + fmt.Println("hashes:", testOptions.hashes) // ratelimits value is if len(testOptions.rls.AsMap()) > 0 {