package utils import ( "encoding/json" "fmt" "io" "log" "net/http" "os" "strings" ) type Hysteria2Response[T any] struct { Ok bool `json:"ok"` Data T `json:"data,omitempty"` Error string `json:"error,omitempty"` } type Hysteria2API struct { authUrl string authToken string statsUrl string statsSecret string client *http.Client } func NewHysteria2API() *Hysteria2API { auth := os.Getenv("H2AUTH") authToken := os.Getenv("H2AUTH_TOKEN") stat := os.Getenv("H2STAT") statsSecret := os.Getenv("H2STAT_SECRET") c := &http.Client{} return &Hysteria2API{auth, authToken, stat, statsSecret, c} } func (a *Hysteria2API) AddUser(username, password string) { req, err := http.NewRequest("POST", a.authUrl+"/add", strings.NewReader(fmt.Sprintf(`{"username":"%s","password":"%s"}`, username, password))) if err != nil { return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", a.authToken) resp, err := a.client.Do(req) if err != nil { return } defer func(Body io.ReadCloser) { _ = Body.Close() }(resp.Body) body, _ := io.ReadAll(resp.Body) log.Println(string(body)) } func (a *Hysteria2API) GetConnectLink(id int, pass string) (string, error) { body := strings.NewReader(fmt.Sprintf(`{"id":%d,"pass":"%s"}`, id, pass)) req, err := http.NewRequest("POST", a.authUrl+"/connect", body) if err != nil { return "", err } req.Header.Set("Content-Type", "application/json") resp, err := a.client.Do(req) if err != nil { return "", err } defer func(Body io.ReadCloser) { _ = Body.Close() }(resp.Body) data, err := io.ReadAll(resp.Body) if err != nil { return "", err } response := new(Hysteria2Response[string]) err = json.Unmarshal(data, response) if err != nil { return "", err } return response.Data, nil }