-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
69 lines (57 loc) · 1.13 KB
/
http.go
File metadata and controls
69 lines (57 loc) · 1.13 KB
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
package hipdate
import (
"encoding/json"
"fmt"
"github.com/3onyc/hipdate/backends"
"github.com/hydrogen18/stoppableListener"
"log"
"net"
"net/http"
)
type HttpServer struct {
l *stoppableListener.StoppableListener
s *http.Server
b backends.Backend
}
func NewHttpServer(b backends.Backend) *HttpServer {
return &HttpServer{
s: &http.Server{},
b: b,
}
}
func (h *HttpServer) Start() error {
l, err := net.Listen("tcp", ":8889")
if err != nil {
return err
}
sl, err := stoppableListener.New(l)
if err != nil {
return err
}
http.HandleFunc("/api/v1/status.json", h.status)
h.l = sl
h.s.Serve(h.l)
return nil
}
func (h *HttpServer) Stop() {
h.l.Stop()
log.Println("NOTICE [http] stopped")
}
func (h *HttpServer) status(rw http.ResponseWriter, req *http.Request) {
rw.Header().Add("Content-Type", "application/json")
hs, err := h.b.ListHosts()
if err != nil {
rw.WriteHeader(500)
fmt.Fprint(rw, err)
return
}
b, err := json.MarshalIndent(hs, "", " ")
if err != nil {
rw.WriteHeader(500)
fmt.Fprint(rw, err)
return
}
if _, err := rw.Write(b); err != nil {
log.Println("ERROR [http]", err)
}
}