Update: add config route
This commit is contained in:
@ -1,9 +1,12 @@
|
||||
package hub
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/Dreamacro/clash/tunnel"
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
"github.com/Dreamacro/clash/proxy"
|
||||
T "github.com/Dreamacro/clash/tunnel"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-chi/render"
|
||||
@ -11,22 +14,26 @@ import (
|
||||
|
||||
func configRouter() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Put("/", updateConfig)
|
||||
r.Get("/", getConfigs)
|
||||
r.Put("/", updateConfigs)
|
||||
return r
|
||||
}
|
||||
|
||||
type General struct {
|
||||
Mode string `json:mode`
|
||||
var modeMapping = map[string]T.Mode{
|
||||
"Global": T.Global,
|
||||
"Rule": T.Rule,
|
||||
"Direct": T.Direct,
|
||||
}
|
||||
|
||||
var modeMapping = map[string]tunnel.Mode{
|
||||
"global": tunnel.Global,
|
||||
"rule": tunnel.Rule,
|
||||
"direct": tunnel.Direct,
|
||||
func getConfigs(w http.ResponseWriter, r *http.Request) {
|
||||
info := listener.Info()
|
||||
mode := tunnel.GetMode().String()
|
||||
info.Mode = &mode
|
||||
render.JSON(w, r, info)
|
||||
}
|
||||
|
||||
func updateConfig(w http.ResponseWriter, r *http.Request) {
|
||||
general := &General{}
|
||||
func updateConfigs(w http.ResponseWriter, r *http.Request) {
|
||||
general := &C.General{}
|
||||
err := render.DecodeJSON(r.Body, general)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
@ -36,14 +43,32 @@ func updateConfig(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
mode, ok := modeMapping[general.Mode]
|
||||
if !ok {
|
||||
// update errors
|
||||
var proxyErr, modeErr error
|
||||
|
||||
// update proxy
|
||||
listener := proxy.Instance()
|
||||
proxyErr = listener.Update(general.AllowLan, general.Port, general.SocksPort)
|
||||
|
||||
// update mode
|
||||
if general.Mode != nil {
|
||||
mode, ok := modeMapping[*general.Mode]
|
||||
if !ok {
|
||||
modeErr = fmt.Errorf("Mode error")
|
||||
} else {
|
||||
tunnel.SetMode(mode)
|
||||
}
|
||||
}
|
||||
|
||||
hasError, errors := formatErrors(map[string]error{
|
||||
"proxy": proxyErr,
|
||||
"mode": modeErr,
|
||||
})
|
||||
|
||||
if hasError {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
render.JSON(w, r, Error{
|
||||
Error: "Mode error",
|
||||
})
|
||||
render.JSON(w, r, errors)
|
||||
return
|
||||
}
|
||||
tun.SetMode(mode)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
Reference in New Issue
Block a user