clash-api: Add more meta api

This commit is contained in:
世界 2025-04-25 11:22:55 +08:00
parent 35aebbd0d9
commit 3c1db46a56
No known key found for this signature in database
GPG Key ID: CD109927C34A63C4
3 changed files with 49 additions and 0 deletions

View File

@ -4,6 +4,7 @@ import (
"bytes"
"net"
"net/http"
"runtime/debug"
"time"
"github.com/sagernet/sing-box/experimental/clashapi/trafficontrol"
@ -12,14 +13,23 @@ import (
"github.com/sagernet/ws/wsutil"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/render"
)
// API created by Clash.Meta
func (s *Server) setupMetaAPI(r chi.Router) {
if s.logDebug {
r := chi.NewRouter()
r.Put("/gc", func(w http.ResponseWriter, r *http.Request) {
debug.FreeOSMemory()
})
r.Mount("/", middleware.Profiler())
}
r.Get("/memory", memory(s.trafficManager))
r.Mount("/group", groupRouter(s))
r.Mount("/upgrade", upgradeRouter(s))
}
type Memory struct {

View File

@ -0,0 +1,36 @@
package clashapi
import (
"net/http"
E "github.com/sagernet/sing/common/exceptions"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
)
func upgradeRouter(server *Server) http.Handler {
r := chi.NewRouter()
r.Post("/ui", updateExternalUI(server))
return r
}
func updateExternalUI(server *Server) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if server.externalUI == "" {
render.Status(r, http.StatusNotFound)
render.JSON(w, r, newError("external UI not enabled"))
return
}
server.logger.Info("upgrading external UI")
err := server.downloadExternalUI()
if err != nil {
server.logger.Error(E.Cause(err, "upgrade external ui"))
render.Status(r, http.StatusInternalServerError)
render.JSON(w, r, newError(err.Error()))
return
}
server.logger.Info("updated external UI")
render.JSON(w, r, render.M{"status": "ok"})
}
}

View File

@ -49,6 +49,8 @@ type Server struct {
httpServer *http.Server
trafficManager *trafficontrol.Manager
urlTestHistory adapter.URLTestHistoryStorage
logDebug bool
mode string
modeList []string
modeUpdateHook chan<- struct{}
@ -74,6 +76,7 @@ func NewServer(ctx context.Context, logFactory log.ObservableFactory, options op
Handler: chiRouter,
},
trafficManager: trafficManager,
logDebug: logFactory.Level() >= log.LevelDebug,
modeList: options.ModeList,
externalController: options.ExternalController != "",
externalUIDownloadURL: options.ExternalUIDownloadURL,