Created
August 19, 2019 12:39
-
-
Save 200sc/ff0a70ac4c56047a7049ec4db70773ff to your computer and use it in GitHub Desktop.
How to lookup a flag from os.Args in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"strings" | |
) | |
func LookupFlag(name string) (value string, found bool) { | |
i := 0 | |
for i < len(os.Args) { | |
flg := os.Args[i] | |
if len(flg) == 0 || flg[0] != '-'{ | |
i++ | |
continue | |
} | |
// we have a flag | |
foundName, val := parseFlag(flg, i) | |
if foundName == name { | |
return val, true | |
} | |
i++ | |
} | |
return "", false | |
} | |
func parseFlag(flag string, atIndex int) (name string, val string) { | |
flag = strings.TrimPrefix(flag, "-") | |
flag = strings.TrimPrefix(flag, "-") | |
if strings.Contains(flag, "=") { | |
split := strings.Split(flag, "=") | |
// This should be safe because of our contains check | |
return split[0], split[1] | |
} | |
// else check the next os arg | |
if len(os.Args) > atIndex+1 { | |
nextFlag := os.Args[atIndex+1] | |
if !strings.HasPrefix(nextFlag, "-") { | |
return flag, nextFlag | |
} | |
} | |
// boolean flag | |
return flag, "true" | |
} | |
func main() { | |
os.Args = []string{"--dogs=2","-cats","false","-horses","--ducks","many"} | |
val, ok := LookupFlag("dogs") | |
fmt.Println(val, ok) | |
val, ok = LookupFlag("cats") | |
fmt.Println(val, ok) | |
val, ok = LookupFlag("horses") | |
fmt.Println(val, ok) | |
val, ok = LookupFlag("cows") | |
fmt.Println(val, ok) | |
val, ok = LookupFlag("ducks") | |
fmt.Println(val, ok) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment