Source file src/flag/example_func_test.go

     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  }
    42  
    43  func ExampleBoolFunc() {
    44  	fs := flag.NewFlagSet("ExampleBoolFunc", flag.ContinueOnError)
    45  	fs.SetOutput(os.Stdout)
    46  
    47  	fs.BoolFunc("log", "logs a dummy message", func(s string) error {
    48  		fmt.Println("dummy message:", s)
    49  		return nil
    50  	})
    51  	fs.Parse([]string{"-log"})
    52  	fs.Parse([]string{"-log=0"})
    53  
    54  	// Output:
    55  	// dummy message: true
    56  	// dummy message: 0
    57  }
    58  

View as plain text