simple_proxy.go 1.35 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
package service

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
)
qunfeng qiu's avatar
qunfeng qiu committed
11 12 13

type SimpleProxy struct {
	regionUrlMap map[string]string
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
}

func NewSimpleProxy(regionUrlMap map[string]string) *SimpleProxy {
	return &SimpleProxy{
		regionUrlMap: regionUrlMap,
	}
}

func (s *SimpleProxy) CountAttackLogs(ctx context.Context, region_code string, serviceID uint32) (int64, error) {
	remoteUrl, err := url.Parse(s.regionUrlMap[region_code])
	if err != nil {
		return 0, err
	}

	remoteUrl = remoteUrl.JoinPath("/api/v2/waf/attack/log/count")

	remoteUrl.RawQuery = fmt.Sprintf("service_id=%d&region_code=%s", serviceID, region_code)
	resp, err := http.Get(remoteUrl.String())
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return 0, fmt.Errorf("failed to count attack logs: %s", resp.Status)
	}
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return 0, err
	}
44 45 46 47 48 49 50 51 52 53

	type Response struct {
		APIVersion string `json:"apiVersion"`
		Code       string `json:"code"`
		Message    string `json:"message"`
		StatusCode int    `json:"status_code"`
		Data       int64  `json:"data"`
	}

	var response Response
54 55 56 57 58 59 60 61
	if err := json.Unmarshal(body, &response); err != nil {
		return 0, err
	}

	if response.Code != "OK" {
		return 0, fmt.Errorf("failed to count attack logs: %s", response.Message)
	}

62
	return response.Data, nil
63 64

}