context.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package context
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/gogf/gf/frame/g"
  6. "sync"
  7. "time"
  8. )
  9. const (
  10. //AccessTokenURL 获取access_token的接口
  11. AccessTokenURL = "https://oapi.dingtalk.com/gettoken"
  12. )
  13. //ResAccessToken 结构体
  14. type ResAccessToken struct {
  15. AccessToken string `json:"access_token"`
  16. ExpiresIn int64 `json:"expires_in"`
  17. Code int64 `json:"errcode"`
  18. Msg string `json:"errmsg"`
  19. }
  20. type Context struct {
  21. *Config
  22. //accessTokenLock 读写锁 同一个AppKey一个
  23. accessTokenLock *sync.RWMutex
  24. }
  25. //SetAccessTokenLock 设置读写锁(一个appID一个读写锁)
  26. func (ctx *Context) SetAccessTokenLock(l *sync.RWMutex) {
  27. ctx.accessTokenLock = l
  28. }
  29. //GetAccessToken 获取access_token
  30. func (ctx *Context) GetAccessToken() (accessToken string, err error) {
  31. ctx.accessTokenLock.Lock()
  32. defer ctx.accessTokenLock.Unlock()
  33. accessTokenCacheKey := fmt.Sprintf("access_token_%s", ctx.AppKey)
  34. val, _ := ctx.Cache.Get(accessTokenCacheKey)
  35. if val != nil {
  36. accessToken = val.(string)
  37. return
  38. }
  39. //从钉钉服务器获取
  40. var resAccessToken ResAccessToken
  41. resAccessToken, err = ctx.GetAccessTokenFromServer()
  42. if err != nil {
  43. return
  44. }
  45. accessToken = resAccessToken.AccessToken
  46. return
  47. }
  48. //CleanAccessTokenCache clean cache
  49. func (ctx *Context) CleanAccessTokenCache() {
  50. accessTokenCacheKey := fmt.Sprintf("access_token_%s", ctx.AppKey)
  51. ctx.Cache.Remove(accessTokenCacheKey)
  52. }
  53. //GetAccessTokenFromServer 强制从服务器获取token
  54. func (ctx *Context) GetAccessTokenFromServer() (token ResAccessToken, err error) {
  55. url := fmt.Sprintf("%s?appkey=%s&appsecret=%s", AccessTokenURL, ctx.AppKey, ctx.AppSecret)
  56. body := g.Client().GetBytes(url)
  57. err = json.Unmarshal(body, &token)
  58. if err != nil {
  59. return
  60. }
  61. if token.Code != 0 {
  62. err = fmt.Errorf("get access_token error : errcode=%v , errormsg=%v", token.Code, token.Msg)
  63. return
  64. }
  65. accessTokenCacheKey := fmt.Sprintf("access_token_%s", ctx.AppKey)
  66. expires := token.ExpiresIn - 1500
  67. err = ctx.Cache.Set(accessTokenCacheKey, token.AccessToken, time.Duration(expires)*time.Second)
  68. return
  69. }