-
Notifications
You must be signed in to change notification settings - Fork 14
/
http.go
71 lines (65 loc) · 1.75 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
package mpv
import "encoding/json"
import "net/http"
// JSONRequest send to the server.
type JSONRequest struct {
Command []interface{} `json:"command"`
}
// JSONResponse send from the server.
type JSONResponse struct {
Err string `json:"error"`
Data interface{} `json:"data"` // May contain float64, bool or string
}
type httpServerHandler struct {
llclient LLClient
}
// HTTPServerHandler returns a http.Handler to access a client via a lowlevel json-api.
// Register as route on your server:
// http.Handle("/mpv", mpv.HTTPHandler(lowlevelclient)
//
// Use api:
// POST http://host/lowlevel Body: { "command": ["get_property", "fullscreen"] }
//
// Result:
// {"error":"success","data":false}
func HTTPServerHandler(client LLClient) http.Handler {
return &httpServerHandler{
llclient: client,
}
}
func (h *httpServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req JSONRequest
dec := json.NewDecoder(r.Body)
err := dec.Decode(&req)
if err != nil {
http.Error(w, "Can not decode request", http.StatusBadRequest)
return
}
resp, err := h.llclient.Exec(req.Command...)
if err != nil {
if err == ErrTimeoutRecv || err == ErrTimeoutSend {
http.Error(w, "Timeout", http.StatusGatewayTimeout)
return
}
// TODO: Handle error, maybe send json response
http.Error(w, "Client returned unknown error", http.StatusInternalServerError)
return
}
jsonResp := JSONResponse{
Err: resp.Err,
Data: resp.Data,
}
b, err := json.Marshal(jsonResp)
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
_, err = w.Write(b)
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
}
}