This commit is contained in:
suyl
2021-07-15 19:04:03 +08:00
parent ee0355d841
commit 6420b5c01e
7 changed files with 271 additions and 29 deletions

View File

@@ -0,0 +1,93 @@
package tibiotapi
import (
"crypto/md5"
"fmt"
"git.rosy.net.cn/baseapi"
"git.rosy.net.cn/baseapi/platformapi"
"git.rosy.net.cn/baseapi/utils"
"net/http"
"strings"
"time"
)
const (
prodURL = "https://api.tibiot.cn/api"
signKey = "password"
)
const (
// ResponseCodeSuccess 操作成功
ResponseCodeSuccess = 0
)
var (
exceedLimitCodes = map[int]int{}
canRetryCodes = map[int]int{}
)
type API struct {
platformapi.APICookie
appID string
appKey string
client *http.Client
config *platformapi.APIConfig
}
func New(appID, appKey string, config ...*platformapi.APIConfig) *API {
curConfig := platformapi.DefAPIConfig
if len(config) > 0 {
curConfig = *config[0]
}
return &API{
appID: appID,
appKey: appKey,
client: &http.Client{Timeout: curConfig.ClientTimeout},
config: &curConfig,
}
}
func (a *API) signParams(apiParams map[string]interface{}) string {
return fmt.Sprintf("%x", md5.Sum([]byte(a.appID+a.appKey+apiParams["timestamp"].(string))))
}
func (a *API) AccessAPI(apiName string, apiParams map[string]interface{}) (retVal interface{}, err error) {
params := utils.MergeMaps(map[string]interface{}{
"app_id": a.appID,
"method": apiName,
}, apiParams)
err = platformapi.AccessPlatformAPIWithRetry(a.client,
func() *http.Request {
params["timestamp"] = utils.Int64ToStr(time.Now().Unix())
sign := a.signParams(params)
params[signKey] = sign
fullURL := prodURL
request, _ := http.NewRequest(http.MethodPost, fullURL, strings.NewReader(utils.Map2URLValues(params).Encode()))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return request
},
a.config,
func(response *http.Response, bodyStr string, jsonResult1 map[string]interface{}) (errLevel string, err error) {
if jsonResult1 == nil {
return platformapi.ErrLevelRecoverableErr, fmt.Errorf("mapData is nil")
}
code := int(utils.Interface2Int64WithDefault(jsonResult1["ret"], ResponseCodeSuccess))
if code == ResponseCodeSuccess {
retVal = jsonResult1["data"]
return platformapi.ErrLevelSuccess, nil
}
newErr := utils.NewErrorIntCode(jsonResult1["msg"].(string), code)
if _, ok := exceedLimitCodes[code]; ok {
return platformapi.ErrLevelExceedLimit, newErr
} else if _, ok := canRetryCodes[code]; ok {
return platformapi.ErrLevelRecoverableErr, newErr
} else {
baseapi.SugarLogger.Debugf("feie AccessAPI failed, jsonResult1:%s", utils.Format4Output(jsonResult1, true))
return platformapi.ErrLevelCodeIsNotOK, newErr
}
})
return retVal, err
}

View File

@@ -0,0 +1,19 @@
package tibiotapi
import (
"git.rosy.net.cn/baseapi"
"go.uber.org/zap"
)
var (
api *API
sugarLogger *zap.SugaredLogger
)
func init() {
logger, _ := zap.NewDevelopment()
sugarLogger = logger.Sugar()
baseapi.Init(sugarLogger)
api = New("1000", "rfBd56ti2SMtYvSg")
}