43 lines
996 B
Go
43 lines
996 B
Go
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
|
|
}
|