Source file src/flag/example_textvar_test.go

     1  // Copyright 2022 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"
    11  	"os"
    12  )
    13  
    14  func ExampleTextVar() {
    15  	fs := flag.NewFlagSet("ExampleTextVar", flag.ContinueOnError)
    16  	fs.SetOutput(os.Stdout)
    17  	var ip net.IP
    18  	fs.TextVar(&ip, "ip", net.IPv4(192, 168, 0, 100), "`IP address` to parse")
    19  	fs.Parse([]string{"-ip", "127.0.0.1"})
    20  	fmt.Printf("{ip: %v}\n\n", ip)
    21  
    22  	// 256 is not a valid IPv4 component
    23  	ip = nil
    24  	fs.Parse([]string{"-ip", "256.0.0.1"})
    25  	fmt.Printf("{ip: %v}\n\n", ip)
    26  
    27  	// Output:
    28  	// {ip: 127.0.0.1}
    29  	//
    30  	// invalid value "256.0.0.1" for flag -ip: invalid IP address: 256.0.0.1
    31  	// Usage of ExampleTextVar:
    32  	//   -ip IP address
    33  	//     	IP address to parse (default 192.168.0.100)
    34  	// {ip: <nil>}
    35  }
    36  

View as plain text