Home

Awesome

flagvar

Coverage

Test Go Reference Go Report Card

A collection of CLI argument types for the flag package.

import "github.com/sgreben/flagvar"

Or just copy & paste what you need. It's public domain.

<!-- TOC --> <!-- /TOC -->

Example

package main

import (
	"flag"
	"fmt"
	"github.com/sgreben/flagvar"
)

var (
	fruit    = flagvar.Enum{Choices: []string{"apple", "banana"}}
	urls     flagvar.URLs
	settings flagvar.Assignments
)

func main() {
	flag.Var(&fruit, "fruit", fmt.Sprintf("set a fruit (%s)", fruit.Help()))
	flag.Var(&urls, "url", "add a URL")
	flag.Var(&settings, "set", fmt.Sprintf("specify a setting (%s)", settings.Help()))
	flag.Parse()
}
$ go run main.go -set abc=xyz -url https://github.com
# no error

$ go run main.go -set abc=xyz -url ://github.com
invalid value "://github.com" for flag -url: parse ://github.com: missing protocol scheme

$ go run main.go -fruit kiwi
invalid value "kiwi" for flag -fruit: "kiwi" must be one of [apple banana]

$ go run main.go -h
Usage:
  -fruit value
        set a fruit (one of [apple banana])
  -set value
        specify a setting (a key/value pair KEY=VALUE)
  -url value
        add a URL

Conventions

Types

Here's a compact overview:

flagvar typeexample CLI argtype of resulting Go value
Alternative
AssignmentKEY=VALUEstruct{Key,Value}
AssignmentsKEY=VALUE[]struct{Key,Value}
AssignmentsMapKEY=VALUEmap[string]string
CIDR127.0.0.1/24struct{IPNet,IP}
CIDRs127.0.0.1/24[]struct{IPNet,IP}
CIDRsCSV127.0.0.1/16,10.1.2.3/8[]struct{IPNet,IP}
Enumapplestring
Enumsapple[]string
EnumsCSVapple,banana[]string
EnumSetapple[]string
EnumSetCSVapple,banana[]string
File./README.mdstring
Files./README.md[]string
Floats1.234[]float64
FloatsCSV1.234,5.0[]float64
Globsrc/**.jsglob.Glob
Globssrc/**.js[]glob.Glob
Ints1002[]int64
IntsCSV123,1002[]int64
IP127.0.0.1net.IP
IPs127.0.0.1[]net.IP
IPsCSV127.0.0.1,10.1.2.3[]net.IP
JSON'{"a":1}'interface{}
JSONs'{"a":1}'[]interface{}
Regexp[a-z]+*regexp.Regexp
Regexps[a-z]+[]*regexp.Regexp
Strings"xyxy"[]string
StringSet"xyxy"[]string
StringSetCSVy,x,y[]string
TCPAddr127.0.0.1:10net.TCPAddr
TCPAddrs127.0.0.1:10[]net.TCPAddr
TCPAddrsCSV127.0.0.1:10,:123[]net.TCPAddr
Template"{{.Size}}"*template.Template
Templates"{{.Size}}"[]*template.Template
TemplateFile"/path/to/template.file"string
Time"10:30 AM"time.Time
Times"10:30 AM"[]time.Time
TimeFormat"RFC3339"string
UDPAddr127.0.0.1:10net.UDPAddr
UDPAddrs127.0.0.1:10[]net.UDPAddr
UDPAddrsCSV127.0.0.1:10,:123[]net.UDPAddr
UnixAddr/example.socknet.UnixAddr
UnixAddrs/example.sock[]net.UnixAddr
UnixAddrsCSV/example.sock,/other.sock[]net.UnixAddr
URLhttps://github.com*url.URL
URLshttps://github.com[]*url.URL
Wrap
WrapCSV
WrapFunc
WrapPointer

Goals / design principles