github.com/TeaOSLab/EdgeNode@v1.3.8/internal/iplibrary/action_http_api.go (about)

     1  package iplibrary
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
     7  	"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
     8  	teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
     9  	"github.com/iwind/TeaGo/maps"
    10  	"net/http"
    11  	"time"
    12  )
    13  
    14  var httpAPIClient = &http.Client{
    15  	Timeout: 5 * time.Second,
    16  }
    17  
    18  type HTTPAPIAction struct {
    19  	BaseAction
    20  
    21  	config *firewallconfigs.FirewallActionHTTPAPIConfig
    22  }
    23  
    24  func NewHTTPAPIAction() *HTTPAPIAction {
    25  	return &HTTPAPIAction{}
    26  }
    27  
    28  func (this *HTTPAPIAction) Init(config *firewallconfigs.FirewallActionConfig) error {
    29  	this.config = &firewallconfigs.FirewallActionHTTPAPIConfig{}
    30  	err := this.convertParams(config.Params, this.config)
    31  	if err != nil {
    32  		return err
    33  	}
    34  
    35  	if len(this.config.URL) == 0 {
    36  		return NewFataError("'url' should not be empty")
    37  	}
    38  
    39  	return nil
    40  }
    41  
    42  func (this *HTTPAPIAction) AddItem(listType IPListType, item *pb.IPItem) error {
    43  	return this.runAction("addItem", listType, item)
    44  }
    45  
    46  func (this *HTTPAPIAction) DeleteItem(listType IPListType, item *pb.IPItem) error {
    47  	return this.runAction("deleteItem", listType, item)
    48  }
    49  
    50  func (this *HTTPAPIAction) runAction(action string, listType IPListType, item *pb.IPItem) error {
    51  	if item == nil {
    52  		return nil
    53  	}
    54  
    55  	// TODO 增加节点ID等信息
    56  	m := maps.Map{
    57  		"action":   action,
    58  		"listType": listType,
    59  		"item": maps.Map{
    60  			"type":      item.Type,
    61  			"ipFrom":    item.IpFrom,
    62  			"ipTo":      item.IpTo,
    63  			"expiredAt": item.ExpiredAt,
    64  		},
    65  	}
    66  	mJSON, err := json.Marshal(m)
    67  	if err != nil {
    68  		return err
    69  	}
    70  	req, err := http.NewRequest(http.MethodPost, this.config.URL, bytes.NewReader(mJSON))
    71  	if err != nil {
    72  		return err
    73  	}
    74  	req.Header.Set("User-Agent", teaconst.GlobalProductName+"-Node/"+teaconst.Version)
    75  	resp, err := httpAPIClient.Do(req)
    76  	if err != nil {
    77  		return err
    78  	}
    79  	_ = resp.Body.Close()
    80  	return nil
    81  }