Skip to content

scax/CachedHttpClient-Go

Repository files navigation

CachedHTTPClient-Go

How to use

Use the DefaultCachedClient

request,err := http.NewRequest("GET","http://example.com",nil)
DefaultCashedClient.Do(request) //not cached
...
DefaultCachedClient.Do(request) //cached
...

Use the DefaultCachedTransport


request, err := http.NewRequest("GET", "http://example.com", nil)
client := http.Client{
	Transport: DefaultCachedTransport,
}

client.Do(request) //not cached
client.Do(request) //cached

Create own CachedTransport

request, err := http.NewRequest("GET", "http://example.com", nil)

cachedTransport := CachedTransport{
	Cache:    NewMapCache(),
	Fallback: http.DefaultTransport,
}

client := http.Client{
	Transport: &cachedTransport,
}

client.Do(request) //not cached
client.Do(request) //cached

Create own Cacher

type MyCache struct {

}

func (m *MyCache) Get(req *http.Request) (*http.Response, error) {
	panic("implement me")
}

func (m *MyCache) Set(req *http.Request, res *http.Response) error {
	panic("implement me")
}

func someFunction() {

	request, err := http.NewRequest("GET", "http://example.com", nil)

	cachedTransport := CachedTransport{
		Cache:    &MyCache{},
		Fallback: http.DefaultTransport,
	}

	client := http.Client{
		Transport: &cachedTransport,
	}

	client.Do(request) //(not cached)
	client.Do(request) //(cached)
}

Caches

Interface Cacher

type Cacher interface {
	Get(req *http.Request) (*http.Response, error)
	Set(req *http.Request, res *http.Response) error
}

MapCache

type MapCache struct {
	cache map[string]*http.Response
	MapCacheOptions
}

type MapCacheOptions struct {
	IgnoreRequestBody            bool
	DontIncludeAllRequestHeaders bool
}

FileCache

type FileCache struct {
	*MapCache
	filePath string
	file     *os.File
}

About

Implements a cached http.client

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages