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 }