• Stars
    star
    132
  • Rank 273,209 (Top 6 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created over 9 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Golang HTTP Cache-Control Parser and Interpretation

cachecontrol: HTTP Caching Parser and Interpretation

PkgGoDevBuild Status

cachecontrol implements RFC 7234 Hypertext Transfer Protocol (HTTP/1.1): Caching. It does this by parsing the Cache-Control and other headers, providing information about requests and responses -- but cachecontrol does not implement an actual cache backend, just the control plane to make decisions about if a particular response is cachable.

Usage

cachecontrol.CachableResponse returns an array of reasons why a response should not be cached and when it expires. In the case that len(reasons) == 0, the response is cachable according to the RFC. However, some people want non-compliant caches for various business use cases, so each reason is specifically named, so if your cache wants to cache POST requests, it can easily do that, but still be RFC compliant in other situations.

Examples

Can you cache Example.com?

package main

import (
	"github.com/pquerna/cachecontrol"

	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	req, _ := http.NewRequest("GET", "http://www.example.com/", nil)

	res, _ := http.DefaultClient.Do(req)
	_, _ = ioutil.ReadAll(res.Body)

	reasons, expires, _ := cachecontrol.CachableResponse(req, res, cachecontrol.Options{})

	fmt.Println("Reasons to not cache: ", reasons)
	fmt.Println("Expiration: ", expires.String())
}

Can I use this in a high performance caching server?

cachecontrol is divided into two packages: cachecontrol with a high level API, and a lower level cacheobject package. Use Object in a high performance use case where you have previously parsed headers containing dates or would like to avoid memory allocations.

package main

import (
	"github.com/pquerna/cachecontrol/cacheobject"

	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	req, _ := http.NewRequest("GET", "http://www.example.com/", nil)

	res, _ := http.DefaultClient.Do(req)
	_, _ = ioutil.ReadAll(res.Body)

	reqDir, _ := cacheobject.ParseRequestCacheControl(req.Header.Get("Cache-Control"))

	resDir, _ := cacheobject.ParseResponseCacheControl(res.Header.Get("Cache-Control"))
	expiresHeader, _ := http.ParseTime(res.Header.Get("Expires"))
	dateHeader, _ := http.ParseTime(res.Header.Get("Date"))
	lastModifiedHeader, _ := http.ParseTime(res.Header.Get("Last-Modified"))

	obj := cacheobject.Object{
		RespDirectives:         resDir,
		RespHeaders:            res.Header,
		RespStatusCode:         res.StatusCode,
		RespExpiresHeader:      expiresHeader,
		RespDateHeader:         dateHeader,
		RespLastModifiedHeader: lastModifiedHeader,

		ReqDirectives: reqDir,
		ReqHeaders:    req.Header,
		ReqMethod:     req.Method,

		NowUTC: time.Now().UTC(),
	}
	rv := cacheobject.ObjectResults{}

	cacheobject.CachableObject(&obj, &rv)
	cacheobject.ExpirationObject(&obj, &rv)

	fmt.Println("Errors: ", rv.OutErr)
	fmt.Println("Reasons to not cache: ", rv.OutReasons)
	fmt.Println("Warning headers to add: ", rv.OutWarnings)
	fmt.Println("Expiration: ", rv.OutExpirationTime.String())
}

Improvements, bugs, adding features, and taking cachecontrol new directions!

Please open issues in Github for ideas, bugs, and general thoughts. Pull requests are of course preferred :)

Credits

cachecontrol has recieved significant contributions from:

License

cachecontrol is licensed under the Apache License, Version 2.0

More Repositories

1

ffjson

faster JSON serialization for Go
Go
2,939
star
2

otp

TOTP library for Go
Go
2,085
star
3

spedye

C
153
star
4

node-logmagic

Lighweight Logging Module for Node.js
JavaScript
80
star
5

node-extension-examples

Examples of writing node.js extensions
C++
78
star
6

selene

A SSL/TLS library
C
74
star
7

ndislocate

A distributed service locator, written on top of Node.js
JavaScript
62
star
8

node-examples

A set of example scripts/servers in Node.js
JavaScript
49
star
9

distsync

[status: prototype] Get files on my servers. Quickly.
Go
23
star
10

termchalk

termchalk: terminal chalkboard utilities for golang
Go
22
star
11

dpop

Go library for DPoP (OAuth 2.0 Demonstration of Proof-of-Possession at the Application Layer)
Go
20
star
12

node-archive

Node.JS Bindings to libarchive
C++
19
star
13

protoc-gen-dynamo

Go
16
star
14

hurl

hurl: hurt a url.
Go
15
star
15

tls-client-hello-stats

Tools to analyze SSL/TLS Client hellos from a packet capture.
Python
14
star
16

ctail

Shell
13
star
17

ckl

Cloudkick Changelog Tool
Shell
10
star
18

bigcass

Cassandra Benchmarking Tools
Python
8
star
19

mod_authn_yubikey

C
8
star
20

ccb

cassandra cloud benchmark
Python
7
star
21

darwintest

HTML
7
star
22

reveal.js-plugin-externalcode

Reveal.js plugin to load Code from external files
JavaScript
6
star
23

node-blanket

JavaScript
4
star
24

protoc-gen-authz

Go
4
star
25

nacl-cryptopp

C++
4
star
26

terribledb

This was a terrible idea
JavaScript
3
star
27

streamplay

streamplay
Go
3
star
28

slides-logs-as-event-streams

JavaScript
3
star
29

qmq

3
star
30

node-xar

Node.js implementation of the XAR file format: http://code.google.com/p/xar/
2
star
31

fastest

this is silly
C
2
star
32

tacua

an experiment in metamorphosis
2
star
33

check_temp

C
2
star
34

trafficserver

C++
2
star
35

qnad

quick network application daemon
2
star
36

redis-slammer

JavaScript
2
star
37

slides-code-reviews

JavaScript
2
star
38

dislocate

A distributed service locator
2
star
39

xjwt

Go library of small extensions for working with JWTs
Go
2
star
40

cassandra

Java
2
star
41

docker-google-auth-proxy

1
star
42

utc.tv

CSS
1
star
43

elderberry

1
star
44

go-keystone-client

Go
1
star
45

megabug-shirts

Parodies of major internet bugs
1
star
46

poc-dsa-verify-CVE-2019-17596

Demonstration of Go's dsa.Verify bug (CVE-2019-17596)
Go
1
star