| 1 |
// Copyright 2020 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 |
"errors" |
| 9 |
"flag" |
| 10 |
"fmt" |
| 11 |
"net" |
| 12 |
"os" |
| 13 |
) |
| 14 |
|
| 15 |
func ExampleFunc() { |
| 16 |
fs := flag.NewFlagSet("ExampleFunc", flag.ContinueOnError) |
| 17 |
fs.SetOutput(os.Stdout) |
| 18 |
var ip net.IP |
| 19 |
fs.Func("ip", "`IP address` to parse", func(s string) error { |
| 20 |
ip = net.ParseIP(s) |
| 21 |
if ip == nil { |
| 22 |
return errors.New("could not parse IP") |
| 23 |
} |
| 24 |
return nil |
| 25 |
}) |
| 26 |
fs.Parse([]string{"-ip", "127.0.0.1"}) |
| 27 |
fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback()) |
| 28 |
|
| 29 |
// 256 is not a valid IPv4 component |
| 30 |
fs.Parse([]string{"-ip", "256.0.0.1"}) |
| 31 |
fmt.Printf("{ip: %v, loopback: %t}\n\n", ip, ip.IsLoopback()) |
| 32 |
|
| 33 |
// Output: |
| 34 |
// {ip: 127.0.0.1, loopback: true} |
| 35 |
// |
| 36 |
// invalid value "256.0.0.1" for flag -ip: could not parse IP |
| 37 |
// Usage of ExampleFunc: |
| 38 |
// -ip IP address |
| 39 |
// IP address to parse |
| 40 |
// {ip: <nil>, loopback: false} |
| 41 |
} |