Skip to content

Commit 6c81002

Browse files
terinjokesianlancetaylor
authored andcommitted
flag: add a Value example
Change-Id: I579cc9f4f8e5be5fd6447a99614797ab7bc53611 Reviewed-on: https://go-review.googlesource.com/120175 Run-TryBot: Ian Lance Taylor <iant@golang.org> TryBot-Result: Gobot Gobot <gobot@golang.org> Reviewed-by: Ian Lance Taylor <iant@golang.org>
1 parent 4b34289 commit 6c81002

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

src/flag/example_value_test.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
5+
package flag_test
6+
7+
import (
8+
"flag"
9+
"fmt"
10+
"net/url"
11+
)
12+
13+
type URLValue struct {
14+
URL *url.URL
15+
}
16+
17+
func (v URLValue) String() string {
18+
if v.URL != nil {
19+
return v.URL.String()
20+
}
21+
return ""
22+
}
23+
24+
func (v URLValue) Set(s string) error {
25+
if u, err := url.Parse(s); err != nil {
26+
return err
27+
} else {
28+
*v.URL = *u
29+
}
30+
return nil
31+
}
32+
33+
var u = &url.URL{}
34+
35+
func ExampleValue() {
36+
fs := flag.NewFlagSet("ExampleValue", flag.ExitOnError)
37+
fs.Var(&URLValue{u}, "url", "URL to parse")
38+
39+
fs.Parse([]string{"-url", "https://golang.org/pkg/flag/"})
40+
fmt.Printf(`{scheme: %q, host: %q, path: %q}`, u.Scheme, u.Host, u.Path)
41+
42+
// Output:
43+
// {scheme: "https", host: "golang.org", path: "/pkg/flag/"}
44+
}

0 commit comments

Comments
 (0)