-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi.go
60 lines (46 loc) · 1.25 KB
/
api.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
package chef
import (
"encoding/json"
"log/slog"
"net/http"
"github.com/sauerbraten/chef/db"
)
type API struct {
http.Handler
db *db.Database
}
func NewAPI(db *db.Database) *API {
api := &API{
db: db,
}
r := http.NewServeMux()
r.HandleFunc("/lookup", api.lookup)
r.HandleFunc("/server", api.server)
api.Handler = withJSONRespHeader(r)
return api
}
func (api *API) lookup(resp http.ResponseWriter, req *http.Request) {
nameOrIP, sorting, last90DaysOnly, directLookupForced, redirected := parseLookupRequest(resp, req)
if redirected {
return
}
results := api.db.Lookup(nameOrIP, sorting, last90DaysOnly, directLookupForced)
err := json.NewEncoder(resp).Encode(results)
if err != nil {
slog.Error("encode lookup results", "error", err)
}
}
func (api *API) server(resp http.ResponseWriter, req *http.Request) {
desc := req.FormValue("q")
results := api.db.FindServerByDescription(desc)
err := json.NewEncoder(resp).Encode(results)
if err != nil {
slog.Error("encode server list", "error", err)
}
}
func withJSONRespHeader(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("Content-Type", "application/json; charset=utf-8")
next.ServeHTTP(resp, req)
})
}