Skip to content

Instantly share code, notes, and snippets.

@iamralch
Created July 6, 2015 20:40
Show Gist options
  • Save iamralch/53a288bd5250b4d443ef to your computer and use it in GitHub Desktop.
Save iamralch/53a288bd5250b4d443ef to your computer and use it in GitHub Desktop.
Custom flag arguments with flag package in Go
package main
import (
"flag"
"fmt"
"net/url"
"strings"
)
type UrlFlag struct {
urls []*url.URL
}
func (arr *UrlFlag) Urls() []*url.URL {
return arr.urls
}
func (arr *UrlFlag) String() string {
return fmt.Sprint(arr.urls)
}
func (arr *UrlFlag) Set(value string) error {
if len(arr.urls) > 0 {
return fmt.Errorf("The url flag is already set")
}
urls := strings.Split(value, ",")
for _, item := range urls {
if parsedUrl, err := url.Parse(item); err != nil {
return err
} else {
arr.urls = append(arr.urls, parsedUrl)
}
}
return nil
}
func main() {
var arg UrlFlag
flag.Var(&arg, "url", "URL comma-separated list")
flag.Parse()
for _, item := range arg.Urls() {
fmt.Printf("scheme: %s url: %s path: %s\n", item.Scheme, item.Host, item.Path)
}
}
@sunliang711
Copy link

great,thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment