-
Notifications
You must be signed in to change notification settings - Fork 17
/
http.go
93 lines (74 loc) · 2.32 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
package dnsp
import (
"encoding/json"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
type httpServer struct {
server *Server
}
func (h *httpServer) index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
w.Header().Set("Content-Type", "text/html")
data, err := Asset("web-ui/index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(data)
}
func (h *httpServer) logo(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
w.Header().Set("Content-Type", "image/png")
data, err := Asset("web-ui/logo.png")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(data)
}
func (h *httpServer) mode(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
mode := "black"
if h.server.white {
mode = "white"
}
w.Write([]byte(`"` + mode + `"`))
}
func (h *httpServer) publicListCount(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
w.Header().Set("Content-Type", "application/json")
n := 0
if !h.server.white {
n = h.server.publicEntriesCount()
}
json.NewEncoder(w).Encode(n)
}
func (h *httpServer) list(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(h.server.privateHostEntries())
}
func (h *httpServer) add(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
w.Header().Set("Content-Type", "application/json")
h.server.addPrivateHostEntry(ps.ByName("url"))
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"status":"ok"}`))
}
func (h *httpServer) remove(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
w.Header().Set("Content-Type", "application/json")
h.server.removePrivateHostEntry(ps.ByName("url"))
w.Write([]byte(`{"status":"ok"}`))
}
func RunHTTPServer(host string, s *Server) {
h := httpServer{server: s}
router := httprouter.New()
router.GET("/", h.index)
router.GET("/logo.png", h.logo)
router.GET("/mode", h.mode)
// Gets the count for the public blacklist
router.GET("/blacklist/public", h.publicListCount)
// Gets the current list
router.GET("/list", h.list)
// Adds a new URL to the list
router.PUT("/list/:url", h.add)
// Removes a URL from the list
router.DELETE("/list/:url", h.remove)
log.Fatal(http.ListenAndServe(host, router))
}