example_value_test.go 845 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package flag_test
  5. import (
  6. "flag"
  7. "fmt"
  8. "net/url"
  9. )
  10. type URLValue struct {
  11. URL *url.URL
  12. }
  13. func (v URLValue) String() string {
  14. if v.URL != nil {
  15. return v.URL.String()
  16. }
  17. return ""
  18. }
  19. func (v URLValue) Set(s string) error {
  20. if u, err := url.Parse(s); err != nil {
  21. return err
  22. } else {
  23. *v.URL = *u
  24. }
  25. return nil
  26. }
  27. var u = &url.URL{}
  28. func ExampleValue() {
  29. fs := flag.NewFlagSet("ExampleValue", flag.ExitOnError)
  30. fs.Var(&URLValue{u}, "url", "URL to parse")
  31. fs.Parse([]string{"-url", "https://golang.org/pkg/flag/"})
  32. fmt.Printf(`{scheme: %q, host: %q, path: %q}`, u.Scheme, u.Host, u.Path)
  33. // Output:
  34. // {scheme: "https", host: "golang.org", path: "/pkg/flag/"}
  35. }