127 lines
2.6 KiB
Go
127 lines
2.6 KiB
Go
package remote
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
type client struct {
|
|
gatewayUrl string
|
|
username string
|
|
password string
|
|
cloudUrl string
|
|
token string
|
|
}
|
|
|
|
var Client client
|
|
|
|
func Init() error {
|
|
// todo 从环境变量中获取参数
|
|
Client = client{
|
|
gatewayUrl: "http://110.40.82.248:9990",
|
|
username: "api",
|
|
password: "123456",
|
|
cloudUrl: "http://103.139.212.110",
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
type PortConfig struct {
|
|
Port string `json:"port"`
|
|
Edge []string `json:"edge"`
|
|
Type string `json:"type"`
|
|
Time int `json:"time"`
|
|
Status bool `json:"status"`
|
|
Rate int `json:"rate"`
|
|
Whitelist []string `json:"whitelist"`
|
|
Userpass string `json:"userpass"`
|
|
AutoEdgeConfig AutoEdgeConfig `json:"auto_edge_config"`
|
|
}
|
|
|
|
type AutoEdgeConfig struct {
|
|
Province string `json:"province"`
|
|
City string `json:"city"`
|
|
Isp string `json:"isp"`
|
|
Count int `json:"count"`
|
|
PacketLoss int `json:"packet_loss"`
|
|
}
|
|
|
|
func (c *client) PortConfigs(params ...PortConfig) error {
|
|
resp, err := c.requestCloud("/port/configs", params)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func(Body io.ReadCloser) {
|
|
_ = Body.Close()
|
|
}(resp.Body)
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return errors.New("failed to configure port")
|
|
}
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var result map[string]any
|
|
err = json.Unmarshal(body, &result)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if result["code"] != 0 {
|
|
return errors.New("failed to configure port")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (c *client) requestGateway(url string, data any) (*http.Response, error) {
|
|
jsonData, err := json.Marshal(data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
req, err := http.NewRequest("POST", c.gatewayUrl+url, strings.NewReader(string(jsonData)))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.SetBasicAuth(c.username, c.password)
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return resp, nil
|
|
}
|
|
|
|
func (c *client) requestCloud(url string, data any) (*http.Response, error) {
|
|
jsonData, err := json.Marshal(data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
req, err := http.NewRequest("POST", c.cloudUrl+url, strings.NewReader(string(jsonData)))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("token", c.token)
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return resp, nil
|
|
}
|