| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- package wx
- import (
- "github.com/silenceper/wechat/oauth"
- "sync"
- "time"
- )
- type tokenTiming struct {
- Token *oauth.ResAccessToken
- Timing time.Time
- }
- var tokenMap map[string]*tokenTiming
- var mutex sync.Mutex
- func init(){
- tokenMap = make(map[string]*tokenTiming)
- tokenCheckLoop()
- }
- func addToken(openId string, token *oauth.ResAccessToken) {
- mutex.Lock()
- defer mutex.Unlock()
- if _, exists := tokenMap[openId]; !exists{
- tokenMap[openId] = &tokenTiming{
- Token: token,
- Timing: time.Now(),
- }
- }
- }
- func getToken(openId string) *oauth.ResAccessToken{
- mutex.Lock()
- defer mutex.Unlock()
- if t, exists := tokenMap[openId]; !exists{
- return nil
- }else{
- return t.Token
- }
- }
- func removeToken(openId string){
- mutex.Lock()
- defer mutex.Unlock()
- if _, exists := tokenMap[openId]; exists{
- delete(tokenMap, openId)
- }
- }
- func tokenCheckLoop(){
- go func(){
- t:=time.NewTicker(10 * 60 * time.Second)
- for {
- select {
- case <-t.C:
- mutex.Lock()
- ks := make([]string, 0)
- for k, v := range tokenMap{
- if time.Now().Sub(v.Timing) > 90 * time.Minute{
- ks = append(ks, k)
- }
- }
- for i := range ks{
- //t, err := wxoauth.RefreshAccessToken(tokenMap[ks[i]].Token.RefreshToken)
- //if err != nil{
- // delete(tokenMap, ks[i])
- // continue
- //}else{
- // tokenMap[ks[i]] = t
- //}
- // 暂时删除不刷新
- delete(tokenMap, ks[i])
- }
- mutex.Unlock()
- }
- }
- }()
- }
|