This commit is contained in:
zzy committed 2026-11-27 18:11:12 +08:00
commit aadfaba7a6
6 files changed
+640

No files matched your search

+148
View File
@@ -0,0 +1,148 @@
package main
import (
"context"
"crypto/subtle"
"embed"
"encoding/json"
"flag"
"io/fs"
"log"
"net/http"
"time"
statsService "github.com/xtls/xray-core/app/stats/command"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
//go:embed web
var webFS embed.FS
// ===== 对应 examples/structures.go =====
type BaseConfig struct {
APIAddress string
APIPort uint16
}
type XrayController struct {
SsClient statsService.StatsServiceClient
CmdConn *grpc.ClientConn
}
// 对应 examples/init.go 的 Init,改用 NewClient
func (x *XrayController) Init(cfg *BaseConfig) error {
addr := cfg.APIAddress + ":" + itoa(uint32(cfg.APIPort))
conn, err := grpc.NewClient(
"passthrough:///"+addr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
return err
}
x.CmdConn = conn
x.SsClient = statsService.NewStatsServiceClient(conn)
return nil
}
func itoa(n uint32) string {
if n == 0 {
return "0"
}
var b [10]byte
i := len(b)
for n > 0 {
i--
b[i] = byte('0' + n%10)
n /= 10
}
return string(b[i:])
}
// HTTP
type Stat struct {
Name string `json:"name"`
Value int64 `json:"value"`
}
type Server struct {
ctl *XrayController
token string
}
func (s *Server) checkAuth(r *http.Request) bool {
if s.token == "" {
return true
}
want := "Bearer " + s.token
return subtle.ConstantTimeCompare(
[]byte(r.Header.Get("Authorization")), []byte(want),
) == 1
}
func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
if !s.checkAuth(r) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
resp, err := s.ctl.SsClient.QueryStats(ctx, &statsService.QueryStatsRequest{})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
out := make([]Stat, 0, len(resp.Stat))
for _, st := range resp.Stat {
out = append(out, Stat{Name: st.Name, Value: st.Value})
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"stat": out})
}
func main() {
var (
listen = flag.String("listen", "127.0.0.1:8080", "HTTP listen address")
apiAddr = flag.String("api-address", "127.0.0.1", "Xray API address")
apiPort = flag.Uint("api-port", 10085, "Xray API port")
token = flag.String("token", "", "Bearer token, empty disables auth")
)
flag.Parse()
cfg := &BaseConfig{
APIAddress: *apiAddr,
APIPort: uint16(*apiPort),
}
ctl := new(XrayController)
if err := ctl.Init(cfg); err != nil {
log.Fatalf("init: %v", err)
}
defer ctl.CmdConn.Close()
srv := &Server{ctl: ctl, token: *token}
mux := http.NewServeMux()
mux.HandleFunc("/stats", srv.handleStats)
sub, err := fs.Sub(webFS, "web")
if err != nil {
log.Fatalf("embed fs: %v", err)
}
mux.Handle("/", http.FileServer(http.FS(sub)))
log.Printf("listening %s | xray %s:%d | auth=%v",
*listen, *apiAddr, *apiPort, *token != "")
log.Fatal(http.ListenAndServe(*listen, mux))
}