Browse Source

clash-api: Add more meta api

世界 5 tháng trước cách đây
mục cha
commit
6c377f16e7

+ 10 - 0
experimental/clashapi/api_meta.go

@@ -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 {

+ 36 - 0
experimental/clashapi/api_meta_upgrade.go

@@ -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"})
+	}
+}

+ 3 - 0
experimental/clashapi/server.go

@@ -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,