forked from davecheney/gcvis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_server.go
80 lines (64 loc) · 1.44 KB
/
http_server.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"
"fmt"
"log"
"net"
"net/http"
"sync"
"time"
)
type HttpServer struct {
graph *Graph
listener net.Listener
iface string
port string
listenerMtx sync.Mutex
}
func NewHttpServer(iface string, port string, graph *Graph) *HttpServer {
h := &HttpServer{
graph: graph,
iface: iface,
port: port,
}
return h
}
func (h *HttpServer) Start() {
serveMux := http.NewServeMux()
serveMux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
h.graph.Write(w)
})
serveMux.HandleFunc("/graph.json", func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
encoder := json.NewEncoder(w)
if err := encoder.Encode(h.graph); err != nil {
log.Fatalf("An error occurred while serving JSON endpoint: %v", err)
}
})
server := http.Server{
Handler: serveMux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
server.Serve(h.Listener())
}
func (h *HttpServer) Close() {
h.Listener().Close()
}
func (h *HttpServer) Url() string {
return fmt.Sprintf("http://%s/", h.Listener().Addr())
}
func (h *HttpServer) Listener() net.Listener {
h.listenerMtx.Lock()
defer h.listenerMtx.Unlock()
if h.listener != nil {
return h.listener
}
ifaceAndPort := fmt.Sprintf("%v:%v", h.iface, h.port)
listener, err := net.Listen("tcp4", ifaceAndPort)
if err != nil {
log.Fatal(err)
}
h.listener = listener
return h.listener
}