httpcache

package module
v0.0.0-...-49a85a9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2020 License: MIT Imports: 11 Imported by: 0

README

httpcache

Example


package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/crhntr/httpcache"
)

func main() {
	const cacheFileName = "/tmp/http_cache"
	cache := new(httpcache.HTTPCache)
	if err := cache.LoadFromFile(cacheFileName); err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err := cache.SaveToFile(cacheFileName); err != nil {
			log.Fatal(err)
		}
	}()

	http.DefaultClient.Transport = cache

	req, _ := http.NewRequest(http.MethodGet, "https://crhntr.com/ip", nil)

	last := time.Now()
	for i := 0; i < 10; i++ {
		res, err := http.DefaultClient.Do(req)
		if err != nil {
			fmt.Println(err)
			continue
		}
		_, _ = io.Copy(os.Stdout, res.Body)
		_ = res.Body.Close()
		fmt.Println(time.Since(last), res.StatusCode)
		last = time.Now()
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type HTTPCache

type HTTPCache struct {
	Transport http.RoundTripper
	TTL       time.Duration
	Cache     sync.Map
}

func (*HTTPCache) GobDecode

func (cache *HTTPCache) GobDecode(in []byte) error

func (*HTTPCache) GobEncode

func (cache *HTTPCache) GobEncode() ([]byte, error)

func (*HTTPCache) Load

func (cache *HTTPCache) Load(reader io.Reader) error

func (*HTTPCache) LoadFromFile

func (cache *HTTPCache) LoadFromFile(fp string) (retErr error)

func (*HTTPCache) RoundTrip

func (cache *HTTPCache) RoundTrip(httpRequest *http.Request) (*http.Response, error)

func (*HTTPCache) Save

func (cache *HTTPCache) Save(writer io.Writer) error

func (*HTTPCache) SaveToFile

func (cache *HTTPCache) SaveToFile(fp string) (retErr error)

type Record

type Record struct {
	Timestamp time.Time
	Request   []byte
	Response  []byte
}

func (Record) GetResponse

func (record Record) GetResponse() (*http.Response, error)

type Request

type Request struct {
	Method      string
	URL         string
	HeadersHash string
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL