Files
proxy/client/report/online.go

70 lines
1.4 KiB
Go

package report
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"proxy-server/client/core"
"proxy-server/client/env"
"strings"
)
func Online(prov, city, isp string) (id int32, 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": env.Name,
"version": core.Version,
})
if err != nil {
return 0, "", err
}
req, err := http.NewRequest("POST", env.EndpointOnline, strings.NewReader(string(body)))
if err != nil {
return 0, "", fmt.Errorf("创建请求失败: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return 0, "", fmt.Errorf("执行请求失败: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, "", errors.New("状态码: " + resp.Status)
}
bytes, err := io.ReadAll(resp.Body)
if err != nil {
return 0, "", fmt.Errorf("读取响应失败: %w", err)
}
var respBody struct {
Id int32 `json:"id"`
Host string `json:"host"`
}
err = json.Unmarshal(bytes, &respBody)
if err != nil {
return 0, "", fmt.Errorf("解析响应失败: %w", err)
}
if respBody.Host == "" {
return 0, "", errors.New("响应体为空")
}
return respBody.Id, respBody.Host, nil
}