mihomo/hub/configs.go

97 lines
1.9 KiB
Go
Raw Normal View History

2018-06-20 22:41:02 +08:00
package hub
import (
2018-07-15 22:23:20 +08:00
"fmt"
2018-06-20 22:41:02 +08:00
"net/http"
"github.com/Dreamacro/clash/config"
2018-07-15 22:23:20 +08:00
C "github.com/Dreamacro/clash/constant"
2018-06-20 22:41:02 +08:00
"github.com/go-chi/chi"
"github.com/go-chi/render"
)
func configRouter() http.Handler {
r := chi.NewRouter()
2018-07-15 22:23:20 +08:00
r.Get("/", getConfigs)
r.Put("/", updateConfigs)
2018-06-20 22:41:02 +08:00
return r
}
type configSchema struct {
2018-08-12 02:23:46 +08:00
Port int `json:"port"`
SocksPort int `json:"socket-port"`
2018-08-26 22:43:38 +08:00
RedirPort int `json:"redir-port"`
2018-08-12 02:23:46 +08:00
AllowLan bool `json:"allow-lan"`
Mode string `json:"mode"`
LogLevel string `json:"log-level"`
}
2018-06-20 22:41:02 +08:00
2018-07-15 22:23:20 +08:00
func getConfigs(w http.ResponseWriter, r *http.Request) {
general := cfg.General()
render.JSON(w, r, configSchema{
2018-08-12 02:23:46 +08:00
Port: general.Port,
SocksPort: general.SocksPort,
2018-08-26 22:43:38 +08:00
RedirPort: general.RedirPort,
2018-08-12 02:23:46 +08:00
AllowLan: general.AllowLan,
Mode: general.Mode.String(),
LogLevel: general.LogLevel.String(),
})
2018-06-20 22:41:02 +08:00
}
2018-07-15 22:23:20 +08:00
func updateConfigs(w http.ResponseWriter, r *http.Request) {
general := &C.General{}
err := render.DecodeJSON(r.Body, general)
2018-06-20 22:41:02 +08:00
if err != nil {
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, Error{
Error: "Format error",
})
return
}
2018-07-15 22:23:20 +08:00
// update errors
2018-08-12 02:23:46 +08:00
var modeErr, logLevelErr error
2018-07-15 22:23:20 +08:00
// update mode
if general.Mode != nil {
mode, ok := config.ModeMapping[*general.Mode]
2018-07-15 22:23:20 +08:00
if !ok {
modeErr = fmt.Errorf("Mode error")
} else {
cfg.SetMode(mode)
2018-07-15 22:23:20 +08:00
}
}
// update log-level
if general.LogLevel != nil {
level, ok := C.LogLevelMapping[*general.LogLevel]
if !ok {
logLevelErr = fmt.Errorf("Log Level error")
} else {
cfg.SetLogLevel(level)
}
}
2018-07-15 22:23:20 +08:00
hasError, errors := formatErrors(map[string]error{
"mode": modeErr,
"log-level": logLevelErr,
2018-07-15 22:23:20 +08:00
})
if hasError {
w.WriteHeader(http.StatusBadRequest)
2018-07-15 22:23:20 +08:00
render.JSON(w, r, errors)
2018-06-20 22:41:02 +08:00
return
}
2018-08-12 02:23:46 +08:00
// update proxy
cfg.UpdateProxy(config.ProxyConfig{
AllowLan: general.AllowLan,
Port: general.Port,
SocksPort: general.SocksPort,
2018-08-26 22:43:38 +08:00
RedirPort: general.RedirPort,
2018-08-12 02:23:46 +08:00
})
2018-06-20 22:41:02 +08:00
w.WriteHeader(http.StatusNoContent)
}