gitee.com/larksuite/oapi-sdk-go/v3@v3.0.3/core/cache.go (about)

     1  /*
     2   * MIT License
     3   *
     4   * Copyright (c) 2022 Lark Technologies Pte. Ltd.
     5   *
     6   * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
     7   *
     8   * The above copyright notice and this permission notice, shall be included in all copies or substantial portions of the Software.
     9   *
    10   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    11   */
    12  
    13  package larkcore
    14  
    15  import (
    16  	"context"
    17  	"sync"
    18  	"time"
    19  )
    20  
    21  var cache = &localCache{}
    22  
    23  func NewCache(config *Config) {
    24  	if config.TokenCache != nil {
    25  		tokenManager = TokenManager{cache: config.TokenCache}
    26  		appTicketManager = AppTicketManager{cache: config.TokenCache}
    27  	}
    28  }
    29  
    30  type Cache interface {
    31  	Set(ctx context.Context, key string, value string, expireTime time.Duration) error
    32  	Get(ctx context.Context, key string) (string, error)
    33  }
    34  
    35  type localCache struct {
    36  	m sync.Map
    37  }
    38  
    39  func (s *localCache) Get(ctx context.Context, key string) (string, error) {
    40  	if val, ok := s.m.Load(key); ok {
    41  		ev := val.(*Value)
    42  		//fmt.Println(fmt.Sprintf("get key:%s,hit cache,time left %f seconds",
    43  		//	key, ev.expireTime.Sub(time.Now()).Seconds()))
    44  		if ev.expireTime.After(time.Now()) {
    45  			return ev.value, nil
    46  		}
    47  	}
    48  	return "", nil
    49  }
    50  
    51  func (s *localCache) Set(ctx context.Context, key, value string, ttl time.Duration) error {
    52  	expireTime := time.Now().Add(ttl)
    53  	s.m.Store(key, &Value{
    54  		value:      value,
    55  		expireTime: expireTime,
    56  	})
    57  	return nil
    58  }
    59  
    60  type Value struct {
    61  	value      string
    62  	expireTime time.Time
    63  }