forked from buffalo-news/geo.bntech.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
80 lines (65 loc) · 1.46 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
package main
import (
"encoding/json"
"io"
"net"
"net/http"
"os/signal"
"syscall"
"time"
)
func httpServer() {
signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM)
http.HandleFunc("/ip", ipRoute)
http.HandleFunc("/stop", stopRoute)
//var err error
httpCloser, _ = listenAndServeWithClose(":3000", nil)
serverLog("HTTP Server started\n")
}
type jsonResponse struct {
Status int
Message string
Body interface{}
}
func jsonRespond(w http.ResponseWriter, status int, msg string, body interface{}) {
response := jsonResponse{status, msg, body}
settingsJSON, _ := json.Marshal(response)
io.WriteString(w, string(settingsJSON))
}
func listenAndServeWithClose(addr string, handler http.Handler) (io.Closer, error) {
var (
listener net.Listener
srvCloser io.Closer
err error
)
srv := &http.Server{Addr: addr, Handler: handler}
if addr == "" {
addr = ":http"
}
listener, err = net.Listen("tcp", addr)
if err != nil {
return nil, err
}
go func() {
err := srv.Serve(tcpKeepAliveListener{listener.(*net.TCPListener)})
if err != nil {
serverLog("HTTP Server Error - %v\n", err)
} else {
serverLog("HTTP call\n")
}
}()
srvCloser = listener
return srvCloser, nil
}
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
}