Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
package mihomoapi
|
||||
|
||||
var leafOutbounds = map[string]bool{
|
||||
"DIRECT": true,
|
||||
"REJECT": true,
|
||||
"REJECT-DROP": true,
|
||||
}
|
||||
|
||||
// ResolveLeafOutbound returns the actual proxy node from a Mihomo chains path.
|
||||
// Policy groups are appended after the leaf dial, so the last chain entry is often a group name.
|
||||
func ResolveLeafOutbound(chains []string, policyGroups map[string]bool) string {
|
||||
if len(chains) == 0 {
|
||||
return ""
|
||||
}
|
||||
for i := len(chains) - 1; i >= 0; i-- {
|
||||
name := chains[i]
|
||||
if leafOutbounds[name] {
|
||||
return name
|
||||
}
|
||||
if policyGroups != nil && policyGroups[name] {
|
||||
continue
|
||||
}
|
||||
return name
|
||||
}
|
||||
return chains[len(chains)-1]
|
||||
}
|
||||
|
||||
func ChainStringsFromAny(raw any) []string {
|
||||
arr, ok := raw.([]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, len(arr))
|
||||
for _, item := range arr {
|
||||
if s, ok := item.(string); ok && s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package mihomoapi
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestResolveLeafOutbound(t *testing.T) {
|
||||
groups := map[string]bool{
|
||||
"PROXY": true,
|
||||
"country_HK": true,
|
||||
"自动选择": true,
|
||||
}
|
||||
cases := []struct {
|
||||
chains []string
|
||||
want string
|
||||
}{
|
||||
{[]string{"PROXY", "sub1_hk_node"}, "sub1_hk_node"},
|
||||
{[]string{"country_HK", "sub1_us_node"}, "sub1_us_node"},
|
||||
{[]string{"PROXY", "自动选择", "sub1_jp_node"}, "sub1_jp_node"},
|
||||
{[]string{"DIRECT"}, "DIRECT"},
|
||||
{[]string{"country_HK"}, "country_HK"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got := ResolveLeafOutbound(tc.chains, groups)
|
||||
if got != tc.want {
|
||||
t.Fatalf("chains=%v want %q got %q", tc.chains, tc.want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package mihomoapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
base string
|
||||
secret string
|
||||
http *http.Client
|
||||
|
||||
mu sync.Mutex
|
||||
proxyCache map[string]ProxyState
|
||||
proxyCacheAt time.Time
|
||||
}
|
||||
|
||||
type ProxyState struct {
|
||||
Type string `json:"type"`
|
||||
Now string `json:"now"`
|
||||
All []string `json:"all"`
|
||||
}
|
||||
|
||||
func New(base, secret string) *Client {
|
||||
return &Client{
|
||||
base: stringsTrimRight(base, "/"),
|
||||
secret: secret,
|
||||
http: &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) ListProxies() (map[string]ProxyState, error) {
|
||||
return c.ListProxiesCached(0)
|
||||
}
|
||||
|
||||
func (c *Client) ListProxiesCached(ttl time.Duration) (map[string]ProxyState, error) {
|
||||
c.mu.Lock()
|
||||
if ttl > 0 && c.proxyCache != nil && time.Since(c.proxyCacheAt) < ttl {
|
||||
out := copyProxyStates(c.proxyCache)
|
||||
c.mu.Unlock()
|
||||
return out, nil
|
||||
}
|
||||
c.mu.Unlock()
|
||||
|
||||
var out struct {
|
||||
Proxies map[string]ProxyState `json:"proxies"`
|
||||
}
|
||||
if err := c.getJSON("/proxies", &out); err != nil {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.proxyCache != nil {
|
||||
return copyProxyStates(c.proxyCache), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if out.Proxies == nil {
|
||||
out.Proxies = map[string]ProxyState{}
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.proxyCache = out.Proxies
|
||||
c.proxyCacheAt = time.Now()
|
||||
c.mu.Unlock()
|
||||
return copyProxyStates(out.Proxies), nil
|
||||
}
|
||||
|
||||
func (c *Client) Reachable() bool {
|
||||
req, err := http.NewRequest(http.MethodGet, c.base+"/version", nil)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if c.secret != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.secret)
|
||||
}
|
||||
client := &http.Client{Timeout: 2 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return resp.StatusCode < 400
|
||||
}
|
||||
|
||||
func copyProxyStates(in map[string]ProxyState) map[string]ProxyState {
|
||||
out := make(map[string]ProxyState, len(in))
|
||||
for k, v := range in {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *Client) SelectProxy(groupName, proxyName string) error {
|
||||
body, _ := json.Marshal(map[string]string{"name": proxyName})
|
||||
return c.putJSON("/proxies/"+url.PathEscape(groupName), body)
|
||||
}
|
||||
|
||||
func (c *Client) getJSON(path string, dest any) error {
|
||||
req, err := http.NewRequest(http.MethodGet, c.base+path, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c.secret != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.secret)
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
return fmt.Errorf("mihomo api %d: %s", resp.StatusCode, string(data))
|
||||
}
|
||||
return json.Unmarshal(data, dest)
|
||||
}
|
||||
|
||||
func (c *Client) putJSON(path string, body []byte) error {
|
||||
req, err := http.NewRequest(http.MethodPut, c.base+path, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if c.secret != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.secret)
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode >= 400 {
|
||||
return fmt.Errorf("mihomo api %d: %s", resp.StatusCode, string(data))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func stringsTrimRight(s, cut string) string {
|
||||
for len(s) > 0 && strings.HasSuffix(s, cut) {
|
||||
s = s[:len(s)-len(cut)]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func IsPolicyGroupType(t string) bool {
|
||||
switch t {
|
||||
case "Selector", "URLTest", "Fallback", "LoadBalance", "Relay":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package mihomoapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ConnectionSnapshot struct {
|
||||
Connections []Connection `json:"connections"`
|
||||
}
|
||||
|
||||
type Connection struct {
|
||||
ID string `json:"id"`
|
||||
Metadata ConnectionMeta `json:"metadata"`
|
||||
Upload int64 `json:"upload"`
|
||||
Download int64 `json:"download"`
|
||||
Start time.Time `json:"start"`
|
||||
Chains []string `json:"chains"`
|
||||
Rule string `json:"rule"`
|
||||
RulePayload string `json:"rulePayload"`
|
||||
}
|
||||
|
||||
type ConnectionMeta struct {
|
||||
Network string `json:"network"`
|
||||
Host string `json:"host"`
|
||||
RemoteDestination string `json:"remoteDestination"`
|
||||
DestinationIP string `json:"destinationIP"`
|
||||
DestinationPort string `json:"destinationPort"`
|
||||
SniffHost string `json:"sniffHost"`
|
||||
}
|
||||
|
||||
func (c *Client) ConnectionSnapshot() (*ConnectionSnapshot, error) {
|
||||
var snap ConnectionSnapshot
|
||||
if err := c.getJSON("/connections", &snap); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &snap, nil
|
||||
}
|
||||
|
||||
// ParseConnectionSnapshot decodes Mihomo /connections JSON.
|
||||
func ParseConnectionSnapshot(data []byte) (*ConnectionSnapshot, error) {
|
||||
var snap ConnectionSnapshot
|
||||
if err := json.Unmarshal(data, &snap); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &snap, nil
|
||||
}
|
||||
|
||||
func (conn *Connection) RequestHost() string {
|
||||
if conn.Metadata.Host != "" {
|
||||
return conn.Metadata.Host
|
||||
}
|
||||
if conn.Metadata.SniffHost != "" {
|
||||
return conn.Metadata.SniffHost
|
||||
}
|
||||
if conn.Metadata.RemoteDestination != "" {
|
||||
return conn.Metadata.RemoteDestination
|
||||
}
|
||||
if conn.Metadata.DestinationIP != "" {
|
||||
return fmt.Sprintf("%s:%s", conn.Metadata.DestinationIP, conn.Metadata.DestinationPort)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (conn *Connection) RuleLine() string {
|
||||
if conn.Rule == "" {
|
||||
return ""
|
||||
}
|
||||
if conn.RulePayload == "" {
|
||||
return conn.Rule
|
||||
}
|
||||
return conn.Rule + "," + conn.RulePayload
|
||||
}
|
||||
|
||||
func (conn *Connection) OutboundNode() string {
|
||||
return ResolveLeafOutbound(conn.Chains, nil)
|
||||
}
|
||||
|
||||
func (conn *Connection) LeafOutbound(policyGroups map[string]bool) string {
|
||||
return ResolveLeafOutbound(conn.Chains, policyGroups)
|
||||
}
|
||||
|
||||
func (conn *Connection) ChainString() string {
|
||||
if len(conn.Chains) == 0 {
|
||||
return ""
|
||||
}
|
||||
b, _ := json.Marshal(conn.Chains)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func (conn *Connection) IsSuccess() bool {
|
||||
for _, ch := range conn.Chains {
|
||||
if ch == "REJECT" || ch == "REJECT-DROP" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return conn.Upload+conn.Download > 0
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package mihomoapi
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestParseConnectionSnapshot(t *testing.T) {
|
||||
raw := []byte(`{
|
||||
"downloadTotal": 200,
|
||||
"uploadTotal": 100,
|
||||
"connections": [{
|
||||
"id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
|
||||
"metadata": {
|
||||
"network": "tcp",
|
||||
"type": "HTTP",
|
||||
"sourceIP": "127.0.0.1",
|
||||
"destinationIP": "142.250.185.78",
|
||||
"destinationPort": "443",
|
||||
"host": "www.google.com"
|
||||
},
|
||||
"upload": 100,
|
||||
"download": 200,
|
||||
"start": "2026-06-16T10:00:00Z",
|
||||
"chains": ["DIRECT"],
|
||||
"rule": "DOMAIN",
|
||||
"rulePayload": "google.com"
|
||||
}],
|
||||
"memory": 0
|
||||
}`)
|
||||
|
||||
snap, err := ParseConnectionSnapshot(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("parse failed: %v", err)
|
||||
}
|
||||
if len(snap.Connections) != 1 {
|
||||
t.Fatalf("expected 1 connection, got %d", len(snap.Connections))
|
||||
}
|
||||
conn := snap.Connections[0]
|
||||
if conn.ID == "" {
|
||||
t.Fatal("expected connection id")
|
||||
}
|
||||
if conn.Metadata.DestinationPort != "443" {
|
||||
t.Fatalf("destination port: %q", conn.Metadata.DestinationPort)
|
||||
}
|
||||
if conn.RequestHost() != "www.google.com" {
|
||||
t.Fatalf("host: %q", conn.RequestHost())
|
||||
}
|
||||
if conn.OutboundNode() != "DIRECT" {
|
||||
t.Fatalf("outbound: %q", conn.OutboundNode())
|
||||
}
|
||||
if conn.Start.IsZero() {
|
||||
t.Fatal("expected start time")
|
||||
}
|
||||
if conn.Start.UTC() != time.Date(2026, 6, 16, 10, 0, 0, 0, time.UTC) {
|
||||
t.Fatalf("unexpected start: %v", conn.Start)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package mihomoapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type TrafficRates struct {
|
||||
Up int64 `json:"up"`
|
||||
Down int64 `json:"down"`
|
||||
UpTotal int64 `json:"upTotal"`
|
||||
DownTotal int64 `json:"downTotal"`
|
||||
}
|
||||
|
||||
// TrafficRates reads the first frame from Mihomo's streaming /traffic endpoint.
|
||||
func (c *Client) TrafficRates(ctx context.Context) (TrafficRates, error) {
|
||||
var zero TrafficRates
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.base+"/traffic", nil)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
if c.secret != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.secret)
|
||||
}
|
||||
client := &http.Client{Timeout: 5 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 400 {
|
||||
return zero, fmt.Errorf("mihomo api %d", resp.StatusCode)
|
||||
}
|
||||
var rates TrafficRates
|
||||
if err := json.NewDecoder(resp.Body).Decode(&rates); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
return rates, nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package mihomoapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTrafficRatesReadsFirstFrame(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
flusher, _ := w.(http.Flusher)
|
||||
_ = json.NewEncoder(w).Encode(TrafficRates{Up: 100, Down: 200})
|
||||
flusher.Flush()
|
||||
time.Sleep(2 * time.Second)
|
||||
_ = json.NewEncoder(w).Encode(TrafficRates{Up: 300, Down: 400})
|
||||
flusher.Flush()
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client := New(srv.URL, "")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
defer cancel()
|
||||
|
||||
rates, err := client.TrafficRates(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("TrafficRates: %v", err)
|
||||
}
|
||||
if rates.Up != 100 || rates.Down != 200 {
|
||||
t.Fatalf("got %+v", rates)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user