flagtype.go 931 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package flagtype defines flag.Value types.
  4. package flagtype
  5. import (
  6. "errors"
  7. "flag"
  8. "fmt"
  9. "math"
  10. "strconv"
  11. "strings"
  12. )
  13. type portValue struct{ n *uint16 }
  14. func PortValue(dst *uint16, defaultPort uint16) flag.Value {
  15. *dst = defaultPort
  16. return portValue{dst}
  17. }
  18. func (p portValue) String() string {
  19. if p.n == nil {
  20. return ""
  21. }
  22. return fmt.Sprint(*p.n)
  23. }
  24. func (p portValue) Set(v string) error {
  25. if v == "" {
  26. return errors.New("can't be the empty string")
  27. }
  28. if strings.Contains(v, ":") {
  29. return errors.New("expecting just a port number, without a colon")
  30. }
  31. n, err := strconv.ParseUint(v, 10, 64) // use 64 instead of 16 to return nicer error message
  32. if err != nil {
  33. return fmt.Errorf("not a valid number")
  34. }
  35. if n > math.MaxUint16 {
  36. return errors.New("out of range for port number")
  37. }
  38. *p.n = uint16(n)
  39. return nil
  40. }