Skip to content

Instantly share code, notes, and snippets.

@song940
Created March 12, 2024 13:10
Show Gist options
  • Save song940/3a2d48f52050ec1332ee7329aed632c6 to your computer and use it in GitHub Desktop.
Save song940/3a2d48f52050ec1332ee7329aed632c6 to your computer and use it in GitHub Desktop.
package cli
import (
"os"
"regexp"
"strings"
)
func ParseArgs() ([]string, map[string]any) {
args := []string{}
flags := map[string]any{}
re := regexp.MustCompile(`^--(\w+)(=(.+))?$`)
for _, arg := range os.Args[1:] {
if re.Match([]byte(arg)) {
p := re.FindStringSubmatch(arg)
k := p[1]
var v any
v = p[3]
if v == "" {
v = true
}
flags[k] = v
} else if strings.HasPrefix(arg, "-") {
for _, v := range arg[1:] {
flags[string(v)] = true
}
} else {
args = append(args, arg)
}
}
return args, flags
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment