-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathweb_api.go
More file actions
47 lines (41 loc) · 1.15 KB
/
web_api.go
File metadata and controls
47 lines (41 loc) · 1.15 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
// ==========================
// web_api.go
// ==========================
package main
import (
"encoding/json"
"net/http"
)
type WebAPI struct {
router *Router
config *ServiceConfigStore
}
func NewWebAPI(router *Router, config *ServiceConfigStore) *WebAPI {
return &WebAPI{router: router, config: config}
}
func (api *WebAPI) Register(mux *http.ServeMux) {
mux.HandleFunc("/v1/services/recommended", api.listRecommended)
mux.HandleFunc("/v1/services/configure", api.configureService)
mux.HandleFunc("/v1/translate", api.router.handleHTTP)
mux.HandleFunc("/v1/stats", api.router.handleStats)
mux.HandleFunc("/v1/ban", api.router.handleBan)
}
func (api *WebAPI) listRecommended(w http.ResponseWriter, _ *http.Request) {
all := api.config.List()
out := []ServiceProfile{}
for _, p := range all {
if p.Recommended {
out = append(out, p)
}
}
json.NewEncoder(w).Encode(out)
}
func (api *WebAPI) configureService(w http.ResponseWriter, r *http.Request) {
var profile ServiceProfile
if err := json.NewDecoder(r.Body).Decode(&profile); err != nil {
http.Error(w, err.Error(), 400)
return
}
api.config.Add(profile)
w.WriteHeader(http.StatusOK)
}