Created
July 6, 2015 20:40
-
-
Save iamralch/53a288bd5250b4d443ef to your computer and use it in GitHub Desktop.
Custom flag arguments with flag package 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 ( | |
"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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
great,thanks