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() // 无则添加,有则更新 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() } } }() }