-
Notifications
You must be signed in to change notification settings - Fork 0
/
flag.go
81 lines (68 loc) · 1.96 KB
/
flag.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"flag"
"fmt"
"os"
"strconv"
)
type Flags struct {
Port int
ProfilePort int
MaxLinks int
MinLinks int
MaxLinkDepth int
MinLinkDepth int
}
func ParseFlags() (Flags, error) {
f := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
var (
port = f.Int("port", getIntEnv("BH_PORT", 8080), "blackhole server port")
profilePort = f.Int("profile-port", getIntEnv("BH_PROFILE_PORT", 0), "blackhole pprofile server port, 0 means pprof server is disabled")
maxLinks = f.Int("max-links", getIntEnv("BH_MAX_LINKS", 50), "max. number of links to generate")
minLinks = f.Int("min-links", getIntEnv("BH_MIN_LINKS", 10), "min. number of links to generate")
maxLinkDepth = f.Int("max-link-depth", getIntEnv("BH_MAX_LINK_DEPTH", 10), "max. link depth (number of path segments)")
minLinkDepth = f.Int("min-link-depth", getIntEnv("BH_MIN_LINK_DEPTH", 1), "min. link depth (number of path segments)")
)
if err := f.Parse(os.Args[1:]); err != nil {
return Flags{}, err
}
//flag.Parse()
flags := Flags{
Port: intValue(port),
ProfilePort: intValue(profilePort),
MaxLinks: intValue(maxLinks),
MinLinks: intValue(minLinks),
MaxLinkDepth: intValue(maxLinkDepth),
MinLinkDepth: intValue(minLinkDepth),
}
err := flags.validate()
return flags, err
}
func (f Flags) validate() error {
if f.Port < 0 || f.Port > 65535 {
return fmt.Errorf("invalid port number: %d", f.Port)
}
if f.ProfilePort < 0 || f.ProfilePort > 65535 {
return fmt.Errorf("invalid profile port number: %d", f.Port)
}
if f.ProfilePort == f.Port {
return fmt.Errorf("profile port and port cannot be the same: %d", f.Port)
}
return nil
}
func getIntEnv(envName string, defaultValue int) int {
env, ok := os.LookupEnv(envName)
if !ok {
return defaultValue
}
if intValue, err := strconv.Atoi(env); err == nil {
return intValue
}
return defaultValue
}
func intValue(v *int) int {
if v == nil {
return 0
}
return *v
}