-
Notifications
You must be signed in to change notification settings - Fork 48
/
server.go
115 lines (97 loc) · 1.98 KB
/
server.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package hub
import (
"encoding/json"
"net/http"
"time"
"github.com/Dreamacro/clash/tunnel"
"github.com/go-chi/chi"
"github.com/go-chi/render"
log "github.com/sirupsen/logrus"
)
var (
tun = tunnel.GetInstance()
)
type Traffic struct {
Up int64 `json:"up"`
Down int64 `json:"down"`
}
type Error struct {
Error string `json:"error"`
}
func NewHub(addr string) {
r := chi.NewRouter()
r.Get("/traffic", traffic)
r.Get("/logs", getLogs)
r.Mount("/configs", configRouter())
err := http.ListenAndServe(addr, r)
if err != nil {
log.Fatalf("External controller error: %s", err.Error())
}
}
func traffic(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
tick := time.NewTicker(time.Second)
t := tun.Traffic()
for range tick.C {
up, down := t.Now()
if err := json.NewEncoder(w).Encode(Traffic{
Up: up,
Down: down,
}); err != nil {
break
}
w.(http.Flusher).Flush()
}
}
type GetLogs struct {
Level string `json:"level"`
}
type Log struct {
Type string `json:"type"`
Payload string `json:"payload"`
}
func getLogs(w http.ResponseWriter, r *http.Request) {
req := &GetLogs{}
render.DecodeJSON(r.Body, req)
if req.Level == "" {
req.Level = "info"
}
mapping := map[string]tunnel.LogLevel{
"info": tunnel.INFO,
"debug": tunnel.DEBUG,
"error": tunnel.ERROR,
"warning": tunnel.WARNING,
}
level, ok := mapping[req.Level]
if !ok {
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, Error{
Error: "Level error",
})
return
}
src := tun.Log()
sub, err := src.Subscribe()
defer src.UnSubscribe(sub)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
render.JSON(w, r, Error{
Error: err.Error(),
})
return
}
render.Status(r, http.StatusOK)
for elm := range sub {
log := elm.(tunnel.Log)
if log.LogLevel > level {
continue
}
if err := json.NewEncoder(w).Encode(Log{
Type: log.Type(),
Payload: log.Payload,
}); err != nil {
break
}
w.(http.Flusher).Flush()
}
}