123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300 |
- package service
- import (
- "bytes"
- "context"
- "crypto/tls"
- "encoding/json"
- "fmt"
- "github.com/davecgh/go-spew/spew"
- v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
- "github.com/spf13/viper"
- "io"
- "net/http"
- "net/url"
- "strings"
- "time"
- )
- type AoDunService interface {
- DomainWhiteList(ctx context.Context, domain string, ip string, apiType string) error
- AddWhiteStaticList(ctx context.Context, req []v1.IpInfo) error
- DelWhiteStaticList(ctx context.Context, id string) error
- GetWhiteStaticList(ctx context.Context,ip string) (int,error)
- }
- func NewAoDunService(
- service *Service,
- conf *viper.Viper,
- ) AoDunService {
- // 1. 创建一个可复用的 Transport,并配置好 TLS 和其他参数
- tr := &http.Transport{
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // 忽略 SSL 验证
- MaxIdleConns: 100, // 最大空闲连接数
- IdleConnTimeout: 90 * time.Second, // 空闲连接超时时间
- }
- // 2. 基于该 Transport 创建一个可复用的 http.Client
- client := &http.Client{
- Transport: tr,
- Timeout: 15 * time.Second, // 设置所有请求的默认超时时间
- }
- return &aoDunService{
- Service: service,
- Url: conf.GetString("aodun.Url"),
- clientID: conf.GetString("aodun.clientID"),
- username: conf.GetString("aodun.username"),
- password: conf.GetString("aodun.password"),
- IPusername: conf.GetString("aodunIp.username"),
- IPpassword: conf.GetString("aodunIp.password"),
- domainUserName: conf.GetString("domainWhite.username"),
- domainPassword: conf.GetString("domainWhite.password"),
- httpClient: client, // 存储共享的 client
- }
- }
- type aoDunService struct {
- *Service
- Url string
- clientID string
- username string
- password string
- IPusername string
- IPpassword string
- domainUserName string
- domainPassword string
- httpClient *http.Client // <--- 新增 http client 字段
- }
- func (s *aoDunService) sendFormData(ctx context.Context, apiUrl string, tokenType string, token string, formData map[string]interface{}) ([]byte, error) {
- URL := s.Url + apiUrl
- jsonData, err := json.Marshal(formData)
- if err != nil {
- return nil, fmt.Errorf("序列化请求数据失败: %w", err)
- }
- // 使用带有 context 的请求,以便上游可以控制请求的取消
- req, err := http.NewRequestWithContext(ctx, "POST", URL, bytes.NewBuffer(jsonData))
- if err != nil {
- return nil, fmt.Errorf("创建 HTTP 请求失败: %w", err)
- }
- // 设置请求头
- req.Header.Set("Content-Type", "application/json")
- // 修正逻辑:当 token 不为空时才设置 Authorization
- if token != "" {
- req.Header.Set("Authorization", tokenType+" "+token)
- }
- // 使用结构体中共享的 httpClient 实例发送请求
- resp, err := s.httpClient.Do(req)
- if err != nil {
- return nil, fmt.Errorf("发送 HTTP 请求失败: %w", err)
- }
- defer resp.Body.Close()
- // 6. 读取响应体内容
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, fmt.Errorf("读取响应体失败: %w", err)
- }
- return body, nil
- }
- func (s *aoDunService) sendDomainFormData(ctx context.Context, domain string, ip string, apiType string) ([]byte, error) {
- var URL string
- if apiType == "add" {
- URL = "http://zapi.zzybgp.com/api/user/do_main"
- } else {
- URL = "http://zapi.zzybgp.com/api/user/do_main/delete"
- }
- formData := url.Values{}
- formData.Set("username", s.domainUserName)
- formData.Set("password", s.domainPassword)
- formData.Add("do_main_list[name][]", domain)
- formData.Add("do_main_list[ip]", ip)
- encodedData := formData.Encode()
- // 使用带有 context 的请求
- req, err := http.NewRequestWithContext(ctx, "POST", URL, bytes.NewBuffer([]byte(encodedData)))
- if err != nil {
- return nil, fmt.Errorf("创建 HTTP 请求失败: %w", err)
- }
- // 设置请求头
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- // 使用共享的 httpClient 实例发送请求
- resp, err := s.httpClient.Do(req)
- if err != nil {
- return nil, fmt.Errorf("发送 HTTP 请求失败: %w", err)
- }
- defer resp.Body.Close()
- // 6. 读取响应体内容
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, fmt.Errorf("读取响应体失败: %w", err)
- }
- return body, nil
- }
- // sendAuthenticatedRequest 封装了需要认证的API请求的通用流程:获取token -> 发送请求。
- func (s *aoDunService) sendAuthenticatedRequest(ctx context.Context, apiPath string, formData map[string]interface{}) ([]byte, error) {
- tokenType, token, err := s.GetToken(ctx)
- if err != nil {
- // 如果获取token失败,直接返回错误
- return nil, err
- }
- // 使用获取到的token发送请求
- return s.sendFormData(ctx, apiPath, tokenType, token, formData)
- }
- func (s *aoDunService) GetToken(ctx context.Context) (string, string, error) {
- formData := map[string]interface{}{
- "ClientID": s.clientID,
- "GrantType": "password",
- "Username": s.IPusername,
- "Password": s.IPpassword,
- }
- resBody, err := s.sendFormData(ctx,"/oauth/token","","",formData)
- if err != nil {
- return "", "", err
- }
- // 7. 将响应体 JSON 数据反序列化到 ResponsePayload 结构体
- var responsePayload v1.GetTokenRespone
- if err := json.Unmarshal(resBody, &responsePayload); err != nil {
- // 如果反序列化失败,可能是响应格式不符合预期
- return "", "", fmt.Errorf("反序列化响应 JSON 失败 ( 内容: %s): %w", string(resBody), err)
- }
- // 8. 检查 API 返回的操作结果代码
- if responsePayload.Code != 0 {
- return "", "", fmt.Errorf("API 错误: code %d, msg '%s', remote_ip '%s'",
- responsePayload.Code, responsePayload.Msg, responsePayload.RemoteIP)
- }
- // 9. 成功:返回 access_token
- if responsePayload.AccessToken == "" {
- // 理论上 code 为 0 时应该有 access_token,这是一个额外的健壮性检查
- return "", "", fmt.Errorf("API 成功 (code 0) 但 access_token 为空")
- }
- return responsePayload.TokenType,responsePayload.AccessToken, nil
- }
- func (s *aoDunService) AddWhiteStaticList(ctx context.Context, req []v1.IpInfo) error {
- formData := map[string]interface{}{
- "action": "add",
- "bwflag": "white",
- "insert_bw_list": req,
- }
- // 使用封装好的方法发送认证请求
- resBody, err := s.sendAuthenticatedRequest(ctx, "/v1.0/firewall/static_bw_list", formData)
- if err != nil {
- return err
- }
- // 7. 将响应体 JSON 数据反序列化到 ResponsePayload 结构体
- var res v1.IpResponse
- if err := json.Unmarshal(resBody, &res); err != nil {
- // 如果反序列化失败,可能是响应格式不符合预期
- return fmt.Errorf("反序列化响应 JSON 失败 ( 内容: %s): %w", string(resBody), err)
- }
- if res.Code != 0 {
- if strings.Contains(res.Msg,"操作部分成功,重复IP如下") {
- s.logger.Info(res.Msg)
- return nil
- }
- return fmt.Errorf("API 错误: code %d, msg '%s'",
- res.Code, res.Msg)
- }
- return nil
- }
- func (s *aoDunService) GetWhiteStaticList(ctx context.Context, ip string) (int, error) {
- formData := map[string]interface{}{
- "action": "get",
- "bwflag": "white",
- "page": 1,
- "ids": ip,
- }
- // 使用封装好的方法发送认证请求
- resBody, err := s.sendAuthenticatedRequest(ctx, "/v1.0/firewall/static_bw_list", formData)
- if err != nil {
- return 0, err
- }
- // 7. 将响应体 JSON 数据反序列化到 ResponsePayload 结构体
- var res v1.IpGetResponse // 使用我们定义的 IpResponse 结构体
- if err := json.Unmarshal(resBody, &res); err != nil {
- // 如果反序列化失败,说明响应格式不符合预期
- return 0, fmt.Errorf("反序列化响应 JSON 失败 (内容: %s): %w", string(resBody), err)
- }
- // 2. 检查 API 返回的 code,这是处理业务失败的关键
- if res.Code != 0 {
- // API 返回了错误码,例如 IP 不存在、参数错误等
- return 0, fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Msg)
- }
- // 3. 检查 data 数组是否为空
- // 即使 code 为 0,也可能因为没有匹配的数据而返回一个空数组
- if len(res.Data) == 0 {
- return 0, fmt.Errorf("API 调用成功,但未找到与 IP '%s' 相关的记录", ip)
- }
- // 4. 获取 ID 并返回
- // 假设我们总是取返回结果中的第一个元素的 ID
- id := res.Data[0].ID
- spew.Dump(id)
- return id, nil // 成功!返回获取到的 id 和 nil 错误
- }
- func (s *aoDunService) DelWhiteStaticList(ctx context.Context, id string) error {
- formData := map[string]interface{}{
- "action": "del",
- "bwflag": "white",
- "flag": 0,
- "ids": id,
- }
- // 使用封装好的方法发送认证请求
- resBody, err := s.sendAuthenticatedRequest(ctx, "/v1.0/firewall/static_bw_list", formData)
- if err != nil {
- return err
- }
- var res v1.IpResponse
- if err := json.Unmarshal(resBody, &res); err != nil {
- return fmt.Errorf("反序列化响应 JSON 失败 ( 内容: %s): %w", string(resBody), err)
- }
- if res.Code != 0 {
- return fmt.Errorf("API 错误: code %d, msg '%s'", res.Code, res.Msg)
- }
- return nil
- }
- func (s *aoDunService) DomainWhiteList(ctx context.Context, domain string, ip string, apiType string) error {
- resBody, err := s.sendDomainFormData(ctx,domain,ip,apiType)
- if err != nil {
- return err
- }
- var res v1.DomainResponse
- if err := json.Unmarshal(resBody, &res); err != nil {
- return fmt.Errorf("反序列化响应 JSON 失败 ( 内容: %s): %w", string(resBody), err)
- }
- if res.Code != 200 && apiType == "add" {
- return fmt.Errorf("API 错误: code %d, msg '%s', data '%s", res.Code, res.Msg, res.Info)
- }
- if res.Code != 600 && apiType == "del" {
- return fmt.Errorf("API 错误: code %d, msg '%s', data '%s", res.Code, res.Msg, res.Info)
- }
- return nil
- }
|