This repository has been archived by the owner on Mar 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
httpcache.go
69 lines (60 loc) · 2.33 KB
/
httpcache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package httpcache
import (
"net/http"
"time"
"github.com/bxcodec/gotcha"
inmemcache "github.com/bxcodec/gotcha/cache"
"github.com/bxcodec/httpcache/cache"
"github.com/bxcodec/httpcache/cache/inmem"
rediscache "github.com/bxcodec/httpcache/cache/redis"
"github.com/go-redis/redis/v8"
"golang.org/x/net/context"
)
// NewWithCustomStorageCache will initiate the httpcache with your defined cache storage
// To use your own cache storage handler, you need to implement the cache.Interactor interface
// And pass it to httpcache.
func NewWithCustomStorageCache(client *http.Client, rfcCompliance bool,
cacheInteractor cache.ICacheInteractor) (cacheHandler *CacheHandler, err error) {
return newClient(client, rfcCompliance, cacheInteractor)
}
func newClient(client *http.Client, rfcCompliance bool,
cacheInteractor cache.ICacheInteractor) (cachedHandler *CacheHandler, err error) {
if client.Transport == nil {
client.Transport = http.DefaultTransport
}
cachedHandler = NewCacheHandlerRoundtrip(client.Transport, rfcCompliance, cacheInteractor)
client.Transport = cachedHandler
return
}
const (
MaxSizeCacheItem = 100
)
// NewWithInmemoryCache will create a complete cache-support of HTTP client with using inmemory cache.
// If the duration not set, the cache will use LFU algorithm
func NewWithInmemoryCache(client *http.Client, rfcCompliance bool, duration ...time.Duration) (cachedHandler *CacheHandler, err error) {
var expiryTime time.Duration
if len(duration) > 0 {
expiryTime = duration[0]
}
c := gotcha.New(
gotcha.NewOption().SetAlgorithm(inmemcache.LRUAlgorithm).
SetExpiryTime(expiryTime).SetMaxSizeItem(MaxSizeCacheItem),
)
return newClient(client, rfcCompliance, inmem.NewCache(c))
}
// NewWithRedisCache will create a complete cache-support of HTTP client with using redis cache.
// If the duration not set, the cache will use LFU algorithm
func NewWithRedisCache(client *http.Client, rfcCompliance bool, options *rediscache.CacheOptions,
duration ...time.Duration) (cachedHandler *CacheHandler, err error) {
var ctx = context.Background()
var expiryTime time.Duration
if len(duration) > 0 {
expiryTime = duration[0]
}
c := redis.NewClient(&redis.Options{
Addr: options.Addr,
Password: options.Password,
DB: options.DB,
})
return newClient(client, rfcCompliance, rediscache.NewCache(ctx, c, expiryTime))
}