forked from krakend/krakend-httpcache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
66 lines (54 loc) · 1.67 KB
/
http.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
// Package httpcache introduces an in-memory-cached http client into the KrakenD stack
package httpcache
import (
"context"
"encoding/json"
"net/http"
"github.com/krakendio/httpcache"
"github.com/luraproject/lura/v2/config"
"github.com/luraproject/lura/v2/transport/http/client"
)
type Cache interface {
// Get returns the []byte representation of a cached response and a bool
// set to true if the value isn't empty
Get(key string) (responseBytes []byte, ok bool)
// Set stores the []byte representation of a response against a key
Set(key string, responseBytes []byte)
// Delete removes the value associated with the key
Delete(key string)
}
// Namespace is the key to use to store and access the custom config data
const Namespace = "github.com/devopsfaith/krakend-httpcache"
// NewHTTPClient creates a HTTPClientFactory using an in-memory-cached http client
func NewHTTPClient(cfg *config.Backend, nextF client.HTTPClientFactory) client.HTTPClientFactory {
raw, ok := cfg.ExtraConfig[Namespace]
if !ok {
return nextF
}
var cache Cache
if b, err := json.Marshal(raw); err == nil {
var opts options
if err := json.Unmarshal(b, &opts); err == nil && opts.Shared {
cache = globalCache
}
}
if cache == nil {
cache = httpcache.NewMemoryCache()
}
return func(ctx context.Context) *http.Client {
httpClient := nextF(ctx)
return &http.Client{
Transport: &httpcache.Transport{
Transport: httpClient.Transport,
Cache: cache,
},
CheckRedirect: httpClient.CheckRedirect,
Jar: httpClient.Jar,
Timeout: httpClient.Timeout,
}
}
}
var globalCache = httpcache.NewMemoryCache()
type options struct {
Shared bool `json:"shared"`
}