lrutripper

package module
v0.0.0-...-e16d7fc Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2023 License: MIT Imports: 13 Imported by: 0

README

lrutripper

A cacheable http.RoundTripper ( net/http ). lrutripper just cache requests in safe methods ( GET, HEAD, OPTIONS )

Why

I want to have something like react-query in wasm projects

Quick start

With net/http

tr := &http.Transport{
	MaxIdleConns:       10,
	IdleConnTimeout:    30 * time.Second,
	DisableCompression: true,
}

// add this
client := &http.Client{Transport: lrutripper.NewCacheableRoundTripper(tr, nil)}

// fetch and cache
resp, err := client.Get("https://example.com")

// cache hit
resp, err := client.Get("https://example.com")

With resty

httpClient := resty.New().SetRetryCount(RetryCount).
  SetRetryWaitTime(RetryWaitTime).
  SetRetryMaxWaitTime(RetryMaxWaitTime).
  AddRetryCondition(
    // RetryConditionFunc type is for retry condition function
    // input: non-nil Response OR request execution error
    func(r *resty.Response, err error) bool {
      return r.StatusCode() == http.StatusTooManyRequests
    },
  )

// add this
rawClient := httpClient.GetClient()
rawClient.Transport = NewCacheableRoundTripper(rawClient.Transport, nil)

// fetch and cache
httpClient.R().Get("https://example.go")

// cache hit
httpClient.R().Get("https://example.go")

Skip and renew cache

ctx := context.Background()

req, err := http.NewRequestWithContext(
  lrutripper.SkipCachedResponse(ctx), http.MethodGet, "https://example.com", nil,
)
resp, err := client.Do(req)

TTL

default ttl is 15 minutes

ctx := context.Background()

req, err := http.NewRequestWithContext(
  lrutripper.TTL(ctx, 10 * time.Minute), http.MethodGet, "https://example.com", nil,
)
resp, err := client.Do(req)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SkipCachedResponse

func SkipCachedResponse(ctx context.Context) context.Context

skip cache hit and renew cache

func TTL

set ttl of cache

Types

type CacheableResponse

type CacheableResponse struct {
	Status     string // e.g. "200 OK"
	StatusCode int    // e.g. 200
	Proto      string // e.g. "HTTP/1.0"
	ProtoMajor int    // e.g. 1
	ProtoMinor int    // e.g. 0

	// Header maps header keys to values. If the response had multiple
	// headers with the same key, they may be concatenated, with comma
	// delimiters.  (RFC 7230, section 3.2.2 requires that multiple headers
	// be semantically equivalent to a comma-delimited sequence.) When
	// Header values are duplicated by other fields in this struct (e.g.,
	// ContentLength, TransferEncoding, Trailer), the field values are
	// authoritative.
	//
	// Keys in the map are canonicalized (see CanonicalHeaderKey).
	Header http.Header

	// Body represents the response body.
	//
	// The response body is streamed on demand as the Body field
	// is read. If the network connection fails or the server
	// terminates the response, Body.Read calls return an error.
	//
	// The http Client and Transport guarantee that Body is always
	// non-nil, even on responses without a body or responses with
	// a zero-length body. It is the caller's responsibility to
	// close Body. The default HTTP client's Transport may not
	// reuse HTTP/1.x "keep-alive" TCP connections if the Body is
	// not read to completion and closed.
	//
	// The Body is automatically dechunked if the server replied
	// with a "chunked" Transfer-Encoding.
	//
	// As of Go 1.12, the Body will also implement io.Writer
	// on a successful "101 Switching Protocols" response,
	// as used by WebSockets and HTTP/2's "h2c" mode.
	Body []byte

	// ContentLength records the length of the associated content. The
	// value -1 indicates that the length is unknown. Unless Request.Method
	// is "HEAD", values >= 0 indicate that the given number of bytes may
	// be read from Body.
	ContentLength int64

	// Contains transfer encodings from outer-most to inner-most. Value is
	// nil, means that "identity" encoding is used.
	TransferEncoding []string

	// Close records whether the header directed that the connection be
	// closed after reading Body. The value is advice for clients: neither
	// ReadResponse nor Response.Write ever closes a connection.
	Close bool

	// Uncompressed reports whether the response was sent compressed but
	// was decompressed by the http package. When true, reading from
	// Body yields the uncompressed content instead of the compressed
	// content actually set from the server, ContentLength is set to -1,
	// and the "Content-Length" and "Content-Encoding" fields are deleted
	// from the responseHeader. To get the original response from
	// the server, set Transport.DisableCompression to true.
	Uncompressed bool

	// Trailer maps trailer keys to values in the same
	// format as Header.
	//
	// The Trailer initially contains only nil values, one for
	// each key specified in the server's "Trailer" header
	// value. Those values are not added to Header.
	//
	// Trailer must not be accessed concurrently with Read calls
	// on the Body.
	//
	// After Body.Read has returned io.EOF, Trailer will contain
	// any trailer values sent by the server.
	Trailer http.Header

	// TLS contains information about the TLS connection on which the
	// response was received. It is nil for unencrypted responses.
	// The pointer is shared between responses and should not be
	// modified.
	TLS *tls.ConnectionState
}

type CacheableRoundTripper

type CacheableRoundTripper struct {
	http.RoundTripper
	// contains filtered or unexported fields
}

func NewCacheableRoundTripper

func NewCacheableRoundTripper(t http.RoundTripper, lru LRUCache) *CacheableRoundTripper

create transport wrapper. This wrapper will cache Response of safe Request

client.Transport = NewCacheableRoundTripper(client.Transport)

func (*CacheableRoundTripper) Hits

func (t *CacheableRoundTripper) Hits() uint64

return count of cache hits

func (*CacheableRoundTripper) RoundTrip

func (t *CacheableRoundTripper) RoundTrip(r *http.Request) (*http.Response, error)

implement RoundTrip for http.RoundTripper

type Key

type Key any

type LRU

type LRU struct {
	*lru.Cache
	// contains filtered or unexported fields
}

LRU provides an LRU cache.

func NewLRU

func NewLRU(maxEntries int) *LRU

NewLRU creates a new Cache. If maxEntries is zero, the cache has no limit.

func (*LRU) Add

func (l *LRU) Add(_ context.Context, k Key, e Value, ttl time.Duration) error

Add adds the entry to the cache.

func (*LRU) Del

func (l *LRU) Del(_ context.Context, k Key)

func (*LRU) Get

func (l *LRU) Get(_ context.Context, k Key) (Value, bool)

Get gets an entry from the cache.

type LRUCache

type LRUCache interface {
	Get(context.Context, Key) (Value, bool)
	Add(context.Context, Key, Value, time.Duration) error
}

type Value

type Value any

Jump to

Keyboard shortcuts

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