Last active
June 30, 2025 14:28
-
-
Save alexedwards/7838faf5f4936e2024657d6e306723e1 to your computer and use it in GitHub Desktop.
Custom command-line flags with flag.Value and encoding.TextUnmarshaler
This file contains hidden or 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 | |
// This example shows how to create a custom command-line flag by implementing | |
// the flag.Value interface. The flag accepts a comma-separated list of values | |
// and stores the contents in a DomainList type, which has the underlying type | |
// []string. | |
// | |
// Use it like: | |
// go run main.go -domains="example.com, example.org" | |
import ( | |
"flag" | |
"fmt" | |
"strings" | |
) | |
type DomainList []string | |
func (d *DomainList) String() string { | |
return strings.Join(*d, ",") | |
} | |
func (d *DomainList) Set(value string) error { | |
domains := strings.Split(value, ",") | |
for i, domain := range domains { | |
domains[i] = strings.TrimSpace(domain) | |
} | |
*d = domains | |
return nil | |
} | |
func main() { | |
var domains DomainList | |
flag.Var(&domains, "domains", "comma-separated list of domains") | |
flag.Parse() | |
fmt.Printf("Domains: %v\n", domains) | |
} |
This file contains hidden or 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 | |
// This example shows how to create a custom command-line flag by implementing | |
// the encoding.TextUnmarshaler interface. The flag accepts a comma-separated | |
// list of values and stores the contents in a DomainList type, which has the | |
// underlying type []string. | |
// | |
// Use it like: | |
// go run main.go -domains="example.com, example.org" | |
import ( | |
"flag" | |
"fmt" | |
"strings" | |
) | |
type DomainList []string | |
func (d *DomainList) UnmarshalText(text []byte) error { | |
domains := strings.Split(string(text), ",") | |
for i, domain := range domains { | |
domains[i] = strings.TrimSpace(domain) | |
} | |
*d = domains | |
return nil | |
} | |
func (d DomainList) MarshalText() ([]byte, error) { | |
return []byte(strings.Join(d, ",")), nil | |
} | |
func main() { | |
var domains DomainList | |
flag.TextVar(&domains, "domains", DomainList{}, "comma-separated list of domains") | |
flag.Parse() | |
fmt.Printf("Domains: %v\n", domains) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment