sing-box/experimental/clashapi/api_meta.go

80 lines
1.6 KiB
Go
Raw Normal View History

2023-04-11 16:43:45 +08:00
package clashapi
import (
"bytes"
2023-11-09 16:59:44 +08:00
"net"
2023-04-11 16:43:45 +08:00
"net/http"
"time"
"github.com/sagernet/sing-box/experimental/clashapi/trafficontrol"
"github.com/sagernet/sing/common/json"
2023-11-09 16:59:44 +08:00
"github.com/sagernet/ws"
"github.com/sagernet/ws/wsutil"
2023-04-11 16:43:45 +08:00
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
)
// API created by Clash.Meta
func (s *Server) setupMetaAPI(r chi.Router) {
r.Get("/memory", memory(s.trafficManager))
r.Mount("/group", groupRouter(s))
}
type Memory struct {
Inuse uint64 `json:"inuse"`
OSLimit uint64 `json:"oslimit"` // maybe we need it in the future
}
func memory(trafficManager *trafficontrol.Manager) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
2023-11-09 16:59:44 +08:00
var conn net.Conn
if r.Header.Get("Upgrade") == "websocket" {
2023-04-11 16:43:45 +08:00
var err error
2023-11-09 16:59:44 +08:00
conn, _, _, err = ws.UpgradeHTTP(r, w)
2023-04-11 16:43:45 +08:00
if err != nil {
return
}
}
2023-11-09 16:59:44 +08:00
if conn == nil {
2023-04-11 16:43:45 +08:00
w.Header().Set("Content-Type", "application/json")
render.Status(r, http.StatusOK)
}
tick := time.NewTicker(time.Second)
defer tick.Stop()
buf := &bytes.Buffer{}
var err error
first := true
for range tick.C {
buf.Reset()
inuse := trafficManager.Snapshot().Memory
// make chat.js begin with zero
// this is shit var,but we need output 0 for first time
if first {
first = false
inuse = 0
}
if err := json.NewEncoder(buf).Encode(Memory{
Inuse: inuse,
OSLimit: 0,
}); err != nil {
break
}
2023-11-09 16:59:44 +08:00
if conn == nil {
2023-04-11 16:43:45 +08:00
_, err = w.Write(buf.Bytes())
w.(http.Flusher).Flush()
} else {
2023-11-09 16:59:44 +08:00
err = wsutil.WriteServerText(conn, buf.Bytes())
2023-04-11 16:43:45 +08:00
}
if err != nil {
break
}
}
}
}