-
Notifications
You must be signed in to change notification settings - Fork 792
/
main.go
100 lines (89 loc) · 2.36 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
// Copyright 2009 The freegeoip authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package apiserver
import (
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
// embed pprof server.
_ "net/http/pprof"
"github.com/prometheus/client_golang/prometheus"
)
// Version tag.
var Version = "3.1.2"
// Run is the entrypoint for the freegeoip server.
func Run() {
c := NewConfig()
c.AddFlags(flag.CommandLine)
sv := flag.Bool("version", false, "Show version and exit")
flag.Parse()
if *sv {
fmt.Printf("freegeoip %s\n", Version)
return
}
if c.LogToStdout {
log.SetOutput(os.Stdout)
}
log.SetPrefix("[freegeoip] ")
f, err := NewHandler(c)
if err != nil {
log.Fatal(err)
}
if c.ServerAddr != "" {
go runServer(c, f)
}
if c.TLSServerAddr != "" {
go runTLSServer(c, f)
}
if c.InternalServerAddr != "" {
go runInternalServer(c)
}
select {}
}
// connStateFunc is a function that can handle connection state.
type connStateFunc func(c net.Conn, s http.ConnState)
// connStateMetrics collect metrics per connection state, per protocol.
// e.g. new http, closed http.
func connStateMetrics(proto string) connStateFunc {
return func(c net.Conn, s http.ConnState) {
switch s {
case http.StateNew:
clientConnsGauge.WithLabelValues(proto).Inc()
case http.StateClosed:
clientConnsGauge.WithLabelValues(proto).Dec()
}
}
}
func runServer(c *Config, f http.Handler) {
log.Println("freegeoip http server starting on", c.ServerAddr)
srv := &http.Server{
Addr: c.ServerAddr,
Handler: f,
ReadTimeout: c.ReadTimeout,
WriteTimeout: c.WriteTimeout,
ErrorLog: c.errorLogger(),
ConnState: connStateMetrics("http"),
}
log.Fatal(srv.ListenAndServe())
}
func runTLSServer(c *Config, f http.Handler) {
log.Println("freegeoip https server starting on", c.TLSServerAddr)
srv := &http.Server{
Addr: c.TLSServerAddr,
Handler: f,
ReadTimeout: c.ReadTimeout,
WriteTimeout: c.WriteTimeout,
ErrorLog: c.errorLogger(),
ConnState: connStateMetrics("https"),
}
log.Fatal(srv.ListenAndServeTLS(c.TLSCertFile, c.TLSKeyFile))
}
func runInternalServer(c *Config) {
http.Handle("/metrics", prometheus.Handler())
log.Println("freegeoip internal server starting on", c.InternalServerAddr)
log.Fatal(http.ListenAndServe(c.InternalServerAddr, nil))
}