/
http.go
116 lines (97 loc) · 2.33 KB
/
http.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
104
105
106
107
108
109
110
111
112
113
114
115
116
package http
import (
"encoding/json"
log "github.com/sirupsen/logrus"
"net"
"net/http"
_ "net/http/pprof"
"time"
"github.com/Cepave/open-falcon-backend/modules/graph/g"
"github.com/Cepave/open-falcon-backend/modules/graph/rrdtool"
)
type Dto struct {
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
var Close_chan, Close_done_chan chan int
func init() {
configCommonRoutes()
configDebugRoutes()
configProcRoutes()
configIndexRoutes()
Close_chan = make(chan int, 1)
Close_done_chan = make(chan int, 1)
}
func RenderJson(w http.ResponseWriter, v interface{}) {
bs, err := json.Marshal(v)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Write(bs)
}
func RenderDataJson(w http.ResponseWriter, data interface{}) {
RenderJson(w, Dto{Msg: "success", Data: data})
}
func RenderMsgJson(w http.ResponseWriter, msg string) {
RenderJson(w, map[string]string{"msg": msg})
}
func AutoRender(w http.ResponseWriter, data interface{}, err error) {
if err != nil {
RenderMsgJson(w, err.Error())
return
}
RenderDataJson(w, data)
}
// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
// connections. It's used by ListenAndServe and ListenAndServeTLS so
// dead TCP connections (e.g. closing laptop mid-download) eventually
// go away.
type TcpKeepAliveListener struct {
*net.TCPListener
}
func (ln TcpKeepAliveListener) Accept() (c net.Conn, err error) {
tc, err := ln.AcceptTCP()
if err != nil {
return
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(3 * time.Minute)
return tc, nil
}
func Start() {
if !g.Config().Http.Enabled {
log.Println("http.Start warning, not enabled")
return
}
if g.Config().Migrate.Enabled {
http.HandleFunc("/counter/migrate",
func(w http.ResponseWriter, r *http.Request) {
RenderDataJson(w, rrdtool.GetCounter())
})
}
addr := g.Config().Http.Listen
if addr == "" {
return
}
s := &http.Server{
Addr: addr,
MaxHeaderBytes: 1 << 30,
}
log.Println("http listening", addr)
ln, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalln(err)
return
}
l := ln.(*net.TCPListener)
go s.Serve(TcpKeepAliveListener{l})
select {
case <-Close_chan:
log.Println("http recv sigout and exit...")
l.Close()
Close_done_chan <- 1
return
}
}