-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
configs.go
73 lines (65 loc) · 1.97 KB
/
configs.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
package clashapi
import (
"net/http"
"strings"
"github.com/sagernet/sing-box/log"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
)
func configRouter(server *Server, logFactory log.Factory, logger log.Logger) http.Handler {
r := chi.NewRouter()
r.Get("/", getConfigs(server, logFactory))
r.Put("/", updateConfigs)
r.Patch("/", patchConfigs(server, logger))
return r
}
type configSchema struct {
Port int `json:"port"`
SocksPort int `json:"socks-port"`
RedirPort int `json:"redir-port"`
TProxyPort int `json:"tproxy-port"`
MixedPort int `json:"mixed-port"`
AllowLan bool `json:"allow-lan"`
BindAddress string `json:"bind-address"`
Mode string `json:"mode"`
LogLevel string `json:"log-level"`
IPv6 bool `json:"ipv6"`
Tun map[string]any `json:"tun"`
}
func getConfigs(server *Server, logFactory log.Factory) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
logLevel := logFactory.Level()
if logLevel == log.LevelTrace {
logLevel = log.LevelDebug
} else if logLevel < log.LevelError {
logLevel = log.LevelError
}
render.JSON(w, r, &configSchema{
Mode: server.mode,
BindAddress: "*",
LogLevel: log.FormatLevel(logLevel),
})
}
}
func patchConfigs(server *Server, logger log.Logger) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
var newConfig configSchema
err := render.DecodeJSON(r.Body, &newConfig)
if err != nil {
render.Status(r, http.StatusBadRequest)
render.JSON(w, r, ErrBadRequest)
return
}
if newConfig.Mode != "" {
mode := strings.ToLower(newConfig.Mode)
if server.mode != mode {
server.mode = mode
logger.Info("updated mode: ", mode)
}
}
render.NoContent(w, r)
}
}
func updateConfigs(w http.ResponseWriter, r *http.Request) {
render.NoContent(w, r)
}