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

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"

	"gitlab.com/tensorsecurity-rd/waf-console/internal/utils"
)
qunfeng qiu's avatar
qunfeng qiu committed
13 14 15

type SimpleProxy struct {
	regionUrlMap map[string]string
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57
}

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
	}
	var response utils.SuccessResponse
	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)
	}

	return response.Data.(int64), nil

}