clash/hub/route/configs.go

103 lines
2.3 KiB
Go
Raw Normal View History

2018-11-21 05:47:46 +00:00
package route
import (
"net/http"
2018-11-30 09:42:40 +00:00
"path/filepath"
2018-11-21 05:47:46 +00:00
"github.com/Dreamacro/clash/hub/executor"
"github.com/Dreamacro/clash/log"
P "github.com/Dreamacro/clash/proxy"
2018-11-28 02:38:30 +00:00
T "github.com/Dreamacro/clash/tunnel"
2018-11-21 05:47:46 +00:00
"github.com/go-chi/chi"
"github.com/go-chi/render"
)
func configRouter() http.Handler {
r := chi.NewRouter()
r.Get("/", getConfigs)
2018-11-30 09:42:40 +00:00
r.Put("/", updateConfigs)
2018-11-28 02:38:30 +00:00
r.Patch("/", patchConfigs)
2018-11-21 05:47:46 +00:00
return r
}
type configSchema struct {
Port *int `json:"port"`
SocksPort *int `json:"socket-port"`
RedirPort *int `json:"redir-port"`
AllowLan *bool `json:"allow-lan"`
Mode *T.Mode `json:"mode"`
LogLevel *log.LogLevel `json:"log-level"`
}
func getConfigs(w http.ResponseWriter, r *http.Request) {
general := executor.GetGeneral()
render.Respond(w, r, general)
}
2018-11-28 02:38:30 +00:00
func pointerOrDefault(p *int, def int) int {
2018-11-21 05:47:46 +00:00
if p != nil {
return *p
}
return def
}
2018-11-28 02:38:30 +00:00
func patchConfigs(w http.ResponseWriter, r *http.Request) {
2018-11-21 05:47:46 +00:00
general := &configSchema{}
if err := render.DecodeJSON(r.Body, general); err != nil {
w.WriteHeader(http.StatusBadRequest)
render.Respond(w, r, ErrBadRequest)
return
}
if general.AllowLan != nil {
P.SetAllowLan(*general.AllowLan)
}
2018-11-28 02:38:30 +00:00
2018-11-21 05:47:46 +00:00
ports := P.GetPorts()
P.ReCreateHTTP(pointerOrDefault(general.Port, ports.Port))
P.ReCreateSocks(pointerOrDefault(general.SocksPort, ports.SocksPort))
P.ReCreateRedir(pointerOrDefault(general.RedirPort, ports.RedirPort))
if general.Mode != nil {
T.Instance().SetMode(*general.Mode)
}
if general.LogLevel != nil {
log.SetLevel(*general.LogLevel)
}
w.WriteHeader(http.StatusNoContent)
}
2018-11-30 09:42:40 +00:00
type updateConfigRequest struct {
2018-12-05 10:19:30 +00:00
Path string `json:"path"`
2018-11-30 09:42:40 +00:00
}
func updateConfigs(w http.ResponseWriter, r *http.Request) {
req := updateConfigRequest{}
if err := render.DecodeJSON(r.Body, &req); err != nil {
w.WriteHeader(http.StatusBadRequest)
render.Respond(w, r, ErrBadRequest)
return
}
if !filepath.IsAbs(req.Path) {
w.WriteHeader(http.StatusBadRequest)
render.Respond(w, r, newError("path is not a absoluted path"))
return
}
force := r.URL.Query().Get("force") == "true"
cfg, err := executor.ParseWithPath(req.Path)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
render.Respond(w, r, newError(err.Error()))
return
}
executor.ApplyConfig(cfg, force)
w.WriteHeader(http.StatusNoContent)
}