Files
proxy/edge/report/report.go

54 lines
1.1 KiB
Go

package report
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"proxy-server/edge/core"
"proxy-server/edge/env"
"strings"
)
func Online() (id int32, host string, err error) {
bytes, err := json.Marshal(map[string]any{
"name": env.Name,
"version": core.Version,
})
if err != nil {
return 0, "", err
}
var body = strings.NewReader(string(bytes))
resp, err := http.Post(env.EndpointOnline, "application/json", body)
if err != nil {
return 0, "", fmt.Errorf("执行请求失败: %w", err)
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
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
}