github.com/sagernet/sing-box@v1.9.0-rc.20/experimental/clashapi/configs.go (about)

     1  package clashapi
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/sagernet/sing-box/log"
     7  
     8  	"github.com/go-chi/chi/v5"
     9  	"github.com/go-chi/render"
    10  )
    11  
    12  func configRouter(server *Server, logFactory log.Factory) http.Handler {
    13  	r := chi.NewRouter()
    14  	r.Get("/", getConfigs(server, logFactory))
    15  	r.Put("/", updateConfigs)
    16  	r.Patch("/", patchConfigs(server))
    17  	return r
    18  }
    19  
    20  type configSchema struct {
    21  	Port        int            `json:"port"`
    22  	SocksPort   int            `json:"socks-port"`
    23  	RedirPort   int            `json:"redir-port"`
    24  	TProxyPort  int            `json:"tproxy-port"`
    25  	MixedPort   int            `json:"mixed-port"`
    26  	AllowLan    bool           `json:"allow-lan"`
    27  	BindAddress string         `json:"bind-address"`
    28  	Mode        string         `json:"mode"`
    29  	LogLevel    string         `json:"log-level"`
    30  	IPv6        bool           `json:"ipv6"`
    31  	Tun         map[string]any `json:"tun"`
    32  }
    33  
    34  func getConfigs(server *Server, logFactory log.Factory) func(w http.ResponseWriter, r *http.Request) {
    35  	return func(w http.ResponseWriter, r *http.Request) {
    36  		logLevel := logFactory.Level()
    37  		if logLevel == log.LevelTrace {
    38  			logLevel = log.LevelDebug
    39  		} else if logLevel < log.LevelError {
    40  			logLevel = log.LevelError
    41  		}
    42  		render.JSON(w, r, &configSchema{
    43  			Mode:        server.mode,
    44  			BindAddress: "*",
    45  			LogLevel:    log.FormatLevel(logLevel),
    46  		})
    47  	}
    48  }
    49  
    50  func patchConfigs(server *Server) func(w http.ResponseWriter, r *http.Request) {
    51  	return func(w http.ResponseWriter, r *http.Request) {
    52  		var newConfig configSchema
    53  		err := render.DecodeJSON(r.Body, &newConfig)
    54  		if err != nil {
    55  			render.Status(r, http.StatusBadRequest)
    56  			render.JSON(w, r, ErrBadRequest)
    57  			return
    58  		}
    59  		if newConfig.Mode != "" {
    60  			server.SetMode(newConfig.Mode)
    61  		}
    62  		render.NoContent(w, r)
    63  	}
    64  }
    65  
    66  func updateConfigs(w http.ResponseWriter, r *http.Request) {
    67  	render.NoContent(w, r)
    68  }