Files
proxy/client/report/online.go

67 lines
1.3 KiB
Go
Raw Normal View History

package report
import (
"encoding/json"
"errors"
"io"
"net/http"
"proxy-server/client/core"
"strings"
)
func Online(prov, city, isp string) (host string, err error) {
var ispInt = 0
switch isp {
case "电信":
ispInt = 1
case "联通":
ispInt = 2
case "移动":
ispInt = 3
}
body, err := json.Marshal(map[string]any{
"prov": prov,
"city": city,
"isp": ispInt,
"name": core.Name,
"version": core.Version,
})
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", core.EndpointOnline, strings.NewReader(string(body)))
if err != nil {
return "", errors.New("创建节点注册请求失败")
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", errors.New("节点注册失败")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", errors.New("节点注册失败,状态码: " + resp.Status)
}
bytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", errors.New("读取节点注册响应失败")
}
var respBody struct {
Host string `json:"host"`
}
err = json.Unmarshal(bytes, &respBody)
if err != nil {
return "", errors.New("解析节点注册响应失败")
}
if respBody.Host == "" {
return "", errors.New("节点注册失败,响应体为空")
}
return respBody.Host, nil
}