-
Notifications
You must be signed in to change notification settings - Fork 27
/
api.go
45 lines (39 loc) · 1013 Bytes
/
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
package api
import (
"encoding/json"
"fmt"
"log"
"github.com/valyala/fasthttp"
"github.com/asciimoo/filtron/proxy"
)
type API struct {
Proxy *proxy.Proxy
RuleFile string
}
func Listen(address, ruleFile string, p *proxy.Proxy) {
log.Println("API listens on", address)
a := &API{p, ruleFile}
fasthttp.ListenAndServe(address, a.Handler)
}
func (a *API) Handler(ctx *fasthttp.RequestCtx) {
ctx.SetContentType("application/json")
ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
switch string(ctx.Path()) {
case "/rules":
j, err := json.Marshal(a.Proxy.Rules)
if err != nil {
ctx.Error(fmt.Sprintf("{\"error\": \"%v\"}", err), 500)
return
}
ctx.Write(j)
case "/rules/reload":
if err := a.Proxy.ReloadRules(a.RuleFile); err != nil {
ctx.Error(fmt.Sprintf("{\"error\": \"%v\"}", err), 500)
return
}
log.Println("Rule file reloaded")
ctx.Write([]byte("{\"status\": \"ok\"}"))
default:
ctx.Error("{\"error\": \"Not found\"}", fasthttp.StatusNotFound)
}
}