风险监控Go语言SDK
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
risk-sdk-go/api.go

92 lines
1.7 KiB

2 years ago
package risk
import (
"context"
"fmt"
"github.com/go-resty/resty/v2"
)
const (
writeLogUri = "/v1/metric/counter/write/v2"
syncUri = "/v1/config/database/sync"
)
type api struct {
http *resty.Client
appId string
appSecret string
}
func NewApi(opts clientOptions) *api {
client := resty.New()
client.SetBaseURL(opts.host)
client.SetTimeout(opts.timeOut)
client.SetRetryCount(2)
client.SetDebug(opts.debug)
client.SetHeader("Content-Type", "application/json")
return &api{
http: client,
appId: opts.appId,
appSecret: opts.appSecret,
}
}
// SyncDatabase 写入访问日志,访问/v1/metric/counter/write/v2接口
func (a *api) WriteLog(ctx context.Context, data *LogData) error {
sign, random, ts := Sign(a.appId, a.appSecret, data)
req := Request{
AppID: a.appId,
Time: int64(ts),
Data: data,
Sign: sign,
Random: random,
}
res, err := a.http.R().
SetBody(req).
Post(writeLogUri)
if err != nil {
return err
}
if res.StatusCode() != 200 {
return fmt.Errorf("write log has error, status_code: %d, response: %s", res.StatusCode(), res.Body())
}
return nil
}
// SyncDatabase 同步数据库数据,访问/v1/config/database/sync接口
func (a *api) SyncDatabase(ctx context.Context, data []*SyncData) error {
sign, random, ts := Sign(a.appId, a.appSecret, data)
req := Request{
AppID: a.appId,
Time: int64(ts),
Data: data,
Sign: sign,
Random: random,
}
res, err := a.http.R().
SetBody(req).
Post(syncUri)
if err != nil {
return err
}
if res.StatusCode() != 200 {
return fmt.Errorf("write log has error, status_code: %d, response: %s", res.StatusCode(), res.Body())
}
return nil
}