- refactor refresh token.
This commit is contained in:
@@ -3,6 +3,7 @@ package weixinapi
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
|
||||
"git.rosy.net.cn/baseapi"
|
||||
"git.rosy.net.cn/baseapi/platformapi"
|
||||
@@ -34,6 +35,7 @@ type API struct {
|
||||
secret string
|
||||
client *http.Client
|
||||
config *platformapi.APIConfig
|
||||
locker sync.RWMutex
|
||||
}
|
||||
|
||||
func New(appID, secret string, config ...*platformapi.APIConfig) *API {
|
||||
@@ -49,6 +51,24 @@ func New(appID, secret string, config ...*platformapi.APIConfig) *API {
|
||||
}
|
||||
}
|
||||
|
||||
func (a *API) SetToken(newToken string) bool {
|
||||
curToken := a.GetToken()
|
||||
if curToken != newToken {
|
||||
a.locker.Lock()
|
||||
defer a.locker.Unlock()
|
||||
a.token = newToken
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *API) GetToken() string {
|
||||
a.locker.RLock()
|
||||
defer a.locker.RUnlock()
|
||||
return a.token
|
||||
}
|
||||
|
||||
func (a *API) AccessAPI(action string, params map[string]interface{}) (retVal interface{}, err error) {
|
||||
if params == nil {
|
||||
panic("params is nil!")
|
||||
@@ -60,11 +80,11 @@ func (a *API) AccessAPI(action string, params map[string]interface{}) (retVal in
|
||||
}
|
||||
params2["appid"] = a.appID
|
||||
params2["secret"] = a.secret
|
||||
url, _ := url.Parse(utils.GenerateGetURL(prodURL, action, params2))
|
||||
fullURL, _ := url.Parse(utils.GenerateGetURL(prodURL, action, params2))
|
||||
// baseapi.SugarLogger.Debug(url.String())
|
||||
request := &http.Request{
|
||||
Method: "GET",
|
||||
URL: url,
|
||||
URL: fullURL,
|
||||
}
|
||||
err = platformapi.AccessPlatformAPIWithRetry(a.client, request, a.config, func(response *http.Response) (result string, err error) {
|
||||
jsonResult1, err := utils.HTTPResponse2Json(response)
|
||||
@@ -108,6 +128,6 @@ func (a *API) RefreshToken() (tokenInfo *TokenInfo, err error) {
|
||||
tokenInfo = result.(*TokenInfo)
|
||||
|
||||
// update my token too.
|
||||
a.token = tokenInfo.AccessToken
|
||||
a.SetToken(tokenInfo.AccessToken)
|
||||
return tokenInfo, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user