-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
103 lines (79 loc) · 1.99 KB
/
main.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"os"
"time"
"github.com/9seconds/topographer/topolib"
"github.com/leaanthony/clir"
)
var version = "dev"
var (
configPath = ""
cli = clir.NewCli("topographer", "A lenient IP geolocation service", version)
errNoConfigPath = errors.New("need to set a config path")
)
const (
DefaultReadTimeout = 10 * time.Second
DefaultWriteTimeout = 10 * time.Second
)
func main() {
cli.StringFlag("config", "A path to config file", &configPath)
cli.Action(mainFunc)
if err := cli.Run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func mainFunc() error {
if configPath == "" {
return errNoConfigPath
}
conf, err := parseConfig(configPath)
if err != nil {
return fmt.Errorf("cannot read config: %w", err)
}
rootCtx, cancel := makeRootContext()
defer cancel()
if err := os.MkdirAll(conf.GetRootDirectory(), 0777); err != nil {
return fmt.Errorf("cannot create root directory %s: %w", conf.GetRootDirectory(), err)
}
providers, err := makeProviders(conf)
if err != nil {
return fmt.Errorf("cannot initialise a list of providers: %w", err)
}
topo, err := topolib.NewTopographer(providers, newLogger(), conf.GetWorkerPoolSize())
if err != nil {
return fmt.Errorf("cannot initialize topographer: %w", err)
}
var httpHandler http.Handler = topo
if conf.HasBasicAuth() {
httpHandler = &basicAuthMiddleware{
handler: httpHandler,
user: conf.GetBasicAuthUser(),
password: conf.GetBasicAuthPassword(),
}
}
srv := &http.Server{
ReadTimeout: DefaultReadTimeout,
WriteTimeout: DefaultWriteTimeout,
Handler: httpHandler,
}
closeChan := make(chan struct{})
go func() {
<-rootCtx.Done()
srv.Shutdown(context.Background()) // nolint: errcheck
close(closeChan)
}()
listener, err := net.Listen("tcp", conf.Listen)
if err != nil {
return fmt.Errorf("cannot start listener: %w", err)
}
defer listener.Close()
srv.Serve(listener) // nolint: errcheck
<-closeChan
return nil
}