- make sugarLogger baseapi globals.

This commit is contained in:
gazebo
2018-06-20 15:51:37 +08:00
parent 55df9f7a2f
commit 21773180a2
7 changed files with 49 additions and 55 deletions

View File

@@ -6,8 +6,8 @@ import (
"net/http" "net/http"
"time" "time"
"git.rosy.net.cn/baseapi"
"git.rosy.net.cn/baseapi/utils" "git.rosy.net.cn/baseapi/utils"
"go.uber.org/zap"
) )
type AccessPlatformAPIWithRetryParams struct { type AccessPlatformAPIWithRetryParams struct {
@@ -16,7 +16,6 @@ type AccessPlatformAPIWithRetryParams struct {
SleepSecondWhenExceedLimit time.Duration SleepSecondWhenExceedLimit time.Duration
Client *http.Client Client *http.Client
Request *http.Request Request *http.Request
SugarLogger *zap.SugaredLogger
} }
const ( const (
@@ -47,7 +46,7 @@ func AccessPlatformAPIWithRetry(params *AccessPlatformAPIWithRetryParams, handle
for { for {
response, err := params.Client.Do(params.Request) response, err := params.Client.Do(params.Request)
if err != nil { if err != nil {
params.SugarLogger.Debugf("client.Get return err:%v", err) baseapi.SugarLogger.Debugf("client.Get return err:%v", err)
err, ok := err.(net.Error) err, ok := err.(net.Error)
recoverableErrorRetryCount++ recoverableErrorRetryCount++
if ok && err.Timeout() && recoverableErrorRetryCount <= params.MaxRecoverableRetryCount { if ok && err.Timeout() && recoverableErrorRetryCount <= params.MaxRecoverableRetryCount {
@@ -58,7 +57,7 @@ func AccessPlatformAPIWithRetry(params *AccessPlatformAPIWithRetryParams, handle
} }
defer response.Body.Close() defer response.Body.Close()
if response.StatusCode != 200 { if response.StatusCode != 200 {
params.SugarLogger.Debugf("http code is:%d", response.StatusCode) baseapi.SugarLogger.Debugf("http code is:%d", response.StatusCode)
recoverableErrorRetryCount++ recoverableErrorRetryCount++
if recoverableErrorRetryCount <= params.MaxRecoverableRetryCount { if recoverableErrorRetryCount <= params.MaxRecoverableRetryCount {
continue continue

View File

@@ -3,6 +3,7 @@ package elmapi
import ( import (
"fmt" "fmt"
"git.rosy.net.cn/baseapi"
"git.rosy.net.cn/baseapi/platform/common" "git.rosy.net.cn/baseapi/platform/common"
"git.rosy.net.cn/baseapi/utils" "git.rosy.net.cn/baseapi/utils"
"github.com/fatih/structs" "github.com/fatih/structs"
@@ -49,7 +50,7 @@ func (e *ELMAPI) unmarshalData(data []byte, msg interface{}) (callbackResponse *
func (e *ELMAPI) CheckRequestValidation(mapData map[string]interface{}) (callbackResponse *ELMCallbackResponse) { func (e *ELMAPI) CheckRequestValidation(mapData map[string]interface{}) (callbackResponse *ELMCallbackResponse) {
sign := e.signParamsMap(mapData, "") sign := e.signParamsMap(mapData, "")
if remoteSign, ok := mapData[signKey].(string); ok && sign != remoteSign { if remoteSign, ok := mapData[signKey].(string); ok && sign != remoteSign {
e.sugarLogger.Infof("Signature is not ok, mine:%v, get:%v", sign, remoteSign) baseapi.SugarLogger.Infof("Signature is not ok, mine:%v, get:%v", sign, remoteSign)
return &ELMCallbackResponse{Message: "signature is invalid"} return &ELMCallbackResponse{Message: "signature is invalid"}
} }
return nil return nil

View File

@@ -10,9 +10,9 @@ import (
"strings" "strings"
"time" "time"
"git.rosy.net.cn/baseapi"
"git.rosy.net.cn/baseapi/platform/common" "git.rosy.net.cn/baseapi/platform/common"
"git.rosy.net.cn/baseapi/utils" "git.rosy.net.cn/baseapi/utils"
"go.uber.org/zap"
) )
const ( const (
@@ -35,12 +35,11 @@ type ELMResult struct {
} }
type ELMAPI struct { type ELMAPI struct {
token string token string
appKey string appKey string
secret string secret string
sugarLogger *zap.SugaredLogger url *url.URL
url *url.URL client *http.Client
client *http.Client
} }
type ELMPayload struct { type ELMPayload struct {
@@ -53,13 +52,12 @@ type ELMPayload struct {
Signature string `json:"signature"` Signature string `json:"signature"`
} }
func NewELMAPI(token, appKey, secret string, sugarLogger *zap.SugaredLogger, isProd bool) *ELMAPI { func NewELMAPI(token, appKey, secret string, isProd bool) *ELMAPI {
api := &ELMAPI{ api := &ELMAPI{
token: token, token: token,
appKey: appKey, appKey: appKey,
secret: secret, secret: secret,
sugarLogger: sugarLogger, client: &http.Client{Timeout: clientTimeout},
client: &http.Client{Timeout: clientTimeout},
} }
if isProd { if isProd {
@@ -87,7 +85,7 @@ func (e *ELMAPI) signParamsMap(mapData map[string]interface{}, prefix string) st
sort.Strings(keyValues) sort.Strings(keyValues)
finalStr := prefix + strings.Join(keyValues, "") + e.secret finalStr := prefix + strings.Join(keyValues, "") + e.secret
// e.sugarLogger.Debugf("sign str:%v", finalStr) // baseapi.SugarLogger.Debugf("sign str:%v", finalStr)
return fmt.Sprintf("%X", md5.Sum([]byte(finalStr))) return fmt.Sprintf("%X", md5.Sum([]byte(finalStr)))
} }
@@ -133,13 +131,12 @@ func (e *ELMAPI) AccessELM(action string, params map[string]interface{}) (retVal
Body: ioutil.NopCloser(strings.NewReader(string(utils.MustMarshal(payload)))), Body: ioutil.NopCloser(strings.NewReader(string(utils.MustMarshal(payload)))),
}, },
SugarLogger: e.sugarLogger,
} }
err = common.AccessPlatformAPIWithRetry(apiAccess, func(response *http.Response) (result string, err error) { err = common.AccessPlatformAPIWithRetry(apiAccess, func(response *http.Response) (result string, err error) {
jsonResult1, err := utils.HttpResponse2Json(response) jsonResult1, err := utils.HttpResponse2Json(response)
if err != nil { if err != nil {
e.sugarLogger.Warnf("HttpResponse2Json return:%v", err) baseapi.SugarLogger.Warnf("HttpResponse2Json return:%v", err)
return common.PAErrorLevelGeneralFail, err return common.PAErrorLevelGeneralFail, err
} }
resultError, _ := jsonResult1["error"].(map[string]interface{}) resultError, _ := jsonResult1["error"].(map[string]interface{})

View File

@@ -5,6 +5,7 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"git.rosy.net.cn/baseapi"
"git.rosy.net.cn/baseapi/platform/common" "git.rosy.net.cn/baseapi/platform/common"
"git.rosy.net.cn/baseapi/utils" "git.rosy.net.cn/baseapi/utils"
) )
@@ -66,7 +67,7 @@ func (j *JDAPI) CheckRequestValidation(request *http.Request) (callbackResponse
sign := j.signParams(mapData) sign := j.signParams(mapData)
if sign != request.FormValue(signKey) { if sign != request.FormValue(signKey) {
j.sugarLogger.Infof("Signature is not ok, mine:%v, get:%v", sign, request.FormValue(signKey)) baseapi.SugarLogger.Infof("Signature is not ok, mine:%v, get:%v", sign, request.FormValue(signKey))
return &JDCallbackResponse{ return &JDCallbackResponse{
Code: JDerrorCodeInvalidSign, Code: JDerrorCodeInvalidSign,
Msg: "signature is invalid", Msg: "signature is invalid",

View File

@@ -10,10 +10,10 @@ import (
"strconv" "strconv"
"time" "time"
"git.rosy.net.cn/baseapi"
"git.rosy.net.cn/baseapi/platform/common" "git.rosy.net.cn/baseapi/platform/common"
"git.rosy.net.cn/baseapi/utils" "git.rosy.net.cn/baseapi/utils"
"go.uber.org/zap"
) )
const ( const (
@@ -56,11 +56,10 @@ const (
) )
type JDAPI struct { type JDAPI struct {
token string token string
appKey string appKey string
appSecret string appSecret string
sugarLogger *zap.SugaredLogger client *http.Client
client *http.Client
} }
var ( var (
@@ -132,8 +131,8 @@ func genGetURL(baseURL, apiStr string, params map[string]string) string {
return fmt.Sprintf(baseURL, apiStr) + fullURL return fmt.Sprintf(baseURL, apiStr) + fullURL
} }
func NewJDAPI(token, appKey, appSecret string, sugarLogger *zap.SugaredLogger) *JDAPI { func NewJDAPI(token, appKey, appSecret string) *JDAPI {
return &JDAPI{token, appKey, appSecret, sugarLogger, &http.Client{Timeout: clientTimeout}} return &JDAPI{token, appKey, appSecret, &http.Client{Timeout: clientTimeout}}
} }
func (j *JDAPI) AccessJDQuery(apiStr string, jdParams map[string]string) (retVal map[string]interface{}, err error) { func (j *JDAPI) AccessJDQuery(apiStr string, jdParams map[string]string) (retVal map[string]interface{}, err error) {
@@ -149,7 +148,7 @@ func (j *JDAPI) AccessJDQuery(apiStr string, jdParams map[string]string) (retVal
} }
jdParamStr, err := json.Marshal(jdParams) jdParamStr, err := json.Marshal(jdParams)
if err != nil { if err != nil {
j.sugarLogger.Errorf("Error when marshal %v, error:%v", jdParams, err) baseapi.SugarLogger.Errorf("Error when marshal %v, error:%v", jdParams, err)
return nil, err return nil, err
} }
params["jd_param_json"] = string(jdParamStr) params["jd_param_json"] = string(jdParamStr)
@@ -168,14 +167,13 @@ func (j *JDAPI) AccessJDQuery(apiStr string, jdParams map[string]string) (retVal
Method: "GET", Method: "GET",
URL: url, URL: url,
}, },
SugarLogger: j.sugarLogger,
} }
err = common.AccessPlatformAPIWithRetry(apiAccess, func(response *http.Response) (errLevel string, err error) { err = common.AccessPlatformAPIWithRetry(apiAccess, func(response *http.Response) (errLevel string, err error) {
jsonResult1, err := utils.HttpResponse2Json(response) jsonResult1, err := utils.HttpResponse2Json(response)
if err != nil { if err != nil {
j.sugarLogger.Warnf("HttpResponse2Json return:%v", err) baseapi.SugarLogger.Warnf("HttpResponse2Json return:%v", err)
return common.PAErrorLevelGeneralFail, err return common.PAErrorLevelGeneralFail, err
} }
@@ -184,7 +182,7 @@ func (j *JDAPI) AccessJDQuery(apiStr string, jdParams map[string]string) (retVal
retVal = jsonResult1 retVal = jsonResult1
return common.PAErrorLevelSuccess, nil return common.PAErrorLevelSuccess, nil
} }
j.sugarLogger.Debugf("jd code is:%s", code) baseapi.SugarLogger.Debugf("jd code is:%s", code)
if _, ok := exceedLimitCodes[code]; ok { if _, ok := exceedLimitCodes[code]; ok {
return common.PAErrorLevelExceedLimit, nil return common.PAErrorLevelExceedLimit, nil
} else if _, ok := canRetryCodes[code]; ok { } else if _, ok := canRetryCodes[code]; ok {

View File

@@ -3,6 +3,7 @@ package mtpsapi
import ( import (
"net/http" "net/http"
"git.rosy.net.cn/baseapi"
"git.rosy.net.cn/baseapi/utils" "git.rosy.net.cn/baseapi/utils"
) )
@@ -42,12 +43,12 @@ func (m *MTPSAPI) CheckRequestValidation(request *http.Request) (callbackRespons
request.ParseForm() request.ParseForm()
sign := m.signParams(request.PostForm) sign := m.signParams(request.PostForm)
if sign != request.FormValue(signKey) { if sign != request.FormValue(signKey) {
m.sugarLogger.Infof("Signature is not ok, mine:%v, get:%v", sign, request.FormValue(signKey)) baseapi.SugarLogger.Infof("Signature is not ok, mine:%v, get:%v", sign, request.FormValue(signKey))
return SignatureIsNotOk return SignatureIsNotOk
} }
for _, valueKey := range []string{"delivery_id", "mt_peisong_id", "order_id"} { for _, valueKey := range []string{"delivery_id", "mt_peisong_id", "order_id"} {
m.sugarLogger.Errorf("Missing mandatory param:%v", valueKey) baseapi.SugarLogger.Errorf("Missing mandatory param:%v", valueKey)
if request.FormValue(valueKey) == "" { if request.FormValue(valueKey) == "" {
return &MtpsCallbackResponse{ return &MtpsCallbackResponse{
Code: -1, Code: -1,

View File

@@ -10,9 +10,9 @@ import (
"strings" "strings"
"time" "time"
"git.rosy.net.cn/baseapi"
"git.rosy.net.cn/baseapi/platform/common" "git.rosy.net.cn/baseapi/platform/common"
"git.rosy.net.cn/baseapi/utils" "git.rosy.net.cn/baseapi/utils"
"go.uber.org/zap"
) )
const ( const (
@@ -122,18 +122,16 @@ type MtpsCreateOrderByShopInfo struct {
} }
type MTPSAPI struct { type MTPSAPI struct {
appKey string appKey string
secret string secret string
sugarLogger *zap.SugaredLogger client *http.Client
client *http.Client
} }
func NewMTPSAPI(appKey, secret string, sugarLogger *zap.SugaredLogger) *MTPSAPI { func NewMTPSAPI(appKey, secret string) *MTPSAPI {
api := &MTPSAPI{ api := &MTPSAPI{
appKey: appKey, appKey: appKey,
secret: secret, secret: secret,
sugarLogger: sugarLogger, client: &http.Client{Timeout: clientTimeout},
client: &http.Client{Timeout: clientTimeout},
} }
return api return api
@@ -156,7 +154,7 @@ func (m *MTPSAPI) signParams(params url.Values) string {
} }
} }
// m.sugarLogger.Debug(finalStr) // baseapi.SugarLogger.Debug(finalStr)
return fmt.Sprintf("%x", sha1.Sum([]byte(finalStr))) return fmt.Sprintf("%x", sha1.Sum([]byte(finalStr)))
} }
@@ -173,29 +171,28 @@ func (m *MTPSAPI) AccessMTPS(action string, params map[string]interface{}) (retV
params2["timestamp"] = []string{utils.Int64ToStr(utils.GetCurTimestamp())} params2["timestamp"] = []string{utils.Int64ToStr(utils.GetCurTimestamp())}
params2["version"] = []string{"1.0"} params2["version"] = []string{"1.0"}
params2[signKey] = []string{m.signParams(params2)} params2[signKey] = []string{m.signParams(params2)}
// m.sugarLogger.Debug(params2.Encode()) // baseapi.SugarLogger.Debug(params2.Encode())
request, _ := http.NewRequest("POST", mtpsAPIURL+"/"+action, strings.NewReader(params2.Encode())) request, _ := http.NewRequest("POST", mtpsAPIURL+"/"+action, strings.NewReader(params2.Encode()))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded") request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
apiAccess := &common.AccessPlatformAPIWithRetryParams{ apiAccess := &common.AccessPlatformAPIWithRetryParams{
MaxExceedLimitRetryCount: maxRetryCountWhenReachLimited, MaxExceedLimitRetryCount: maxRetryCountWhenReachLimited,
MaxRecoverableRetryCount: maxRetryCountWhenNetworkException, MaxRecoverableRetryCount: maxRetryCountWhenNetworkException,
SleepSecondWhenExceedLimit: sleepSecondWhenLimited, SleepSecondWhenExceedLimit: sleepSecondWhenLimited,
Client: m.client, Client: m.client,
Request: request, Request: request,
SugarLogger: m.sugarLogger,
} }
err = common.AccessPlatformAPIWithRetry(apiAccess, func(response *http.Response) (result string, err error) { err = common.AccessPlatformAPIWithRetry(apiAccess, func(response *http.Response) (result string, err error) {
jsonResult1, err := utils.HttpResponse2Json(response) jsonResult1, err := utils.HttpResponse2Json(response)
if err != nil { if err != nil {
m.sugarLogger.Warnf("HttpResponse2Json return:%v", err) baseapi.SugarLogger.Warnf("HttpResponse2Json return:%v", err)
return common.PAErrorLevelGeneralFail, err return common.PAErrorLevelGeneralFail, err
} }
code := int(utils.MustInterface2Int64(jsonResult1["code"])) code := int(utils.MustInterface2Int64(jsonResult1["code"]))
retVal = &MTPSResult{ retVal = &MTPSResult{
Code: code, Code: code,
} }
m.sugarLogger.Debug(jsonResult1) baseapi.SugarLogger.Debug(jsonResult1)
if code == ResponseCodeSuccess { if code == ResponseCodeSuccess {
if innerData, ok := jsonResult1["data"]; ok { if innerData, ok := jsonResult1["data"]; ok {
retVal.Data, _ = innerData.(map[string]interface{}) retVal.Data, _ = innerData.(map[string]interface{})
@@ -242,7 +239,7 @@ func (m *MTPSAPI) CreateOrderByShop(basicParams *MtpsCreateOrderByShopInfo, addP
delete(params, "expected_delivery_time") delete(params, "expected_delivery_time")
} }
if result, err := m.AccessMTPS("order/createByShop", params); err != nil { if result, err := m.AccessMTPS("order/createByShop", params); err != nil {
m.sugarLogger.Debugf("result:%v", result) baseapi.SugarLogger.Debugf("result:%v", result)
return nil, utils.NewErrorIntCode(err.Error(), result.Code) return nil, utils.NewErrorIntCode(err.Error(), result.Code)
} else { } else {
return m.result2OrderResponse(result), nil return m.result2OrderResponse(result), nil
@@ -269,7 +266,7 @@ func (m *MTPSAPI) CancelOrder(deliveryId int64, mtPeiSongId string, cancelReason
"cancel_reason": cancelReason, "cancel_reason": cancelReason,
} }
if result, err := m.AccessMTPS("order/delete", params); err != nil { if result, err := m.AccessMTPS("order/delete", params); err != nil {
m.sugarLogger.Debugf("result:%v", result) baseapi.SugarLogger.Debugf("result:%v", result)
return nil, err return nil, err
} else { } else {
return m.result2OrderResponse(result), nil return m.result2OrderResponse(result), nil