cookiejar

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2024 License: BSD-3-Clause Imports: 19 Imported by: 4

README

Cookiejar

GitHub Releases Build Status codecov Go Report Card GoDevDoc Donate

The Persistent Cookiejar is a fork of net/http/cookiejar which also implements methods for persisting the cookies to a filesystem and retrieving them using spf13/afero

Prerequisites

  • Go >= 1.23

Install

go get go.nhat.io/cookiejar

Usage

Construct the cookiejar with the following options:

Option Description Default Value
WithFilePath The path to the file to store the cookies "cookies.json"
WithFilePerm The file permission to use for persisting the cookies 0600
WithAutoSync Whether to automatically sync the cookies to the file after each request false
WithLogger The logger to use for logging No log
WithFs The filesystem to use for persisting the cookies afero.NewOsFs()
WithSerDer The serializer/deserializer to use for persisting the cookies json
WithPublicSuffixList The public suffix list to use for cookie domain matching
All users of cookiejar should import golang.org/x/net/publicsuffix
nil

Example:

package example

import (
	"net/http"

	"go.nhat.io/cookiejar"
)

func newClient() *http.Client {
	jar := cookiejar.NewPersistentJar(
		cookiejar.WithFilePath("/path/to/cookies.json"),
		cookiejar.WithFilePerm(0755),
		cookiejar.WithAutoSync(true),
	)

	return &http.Client{
		Jar: jar,
	}
}

Examples

package cookiejar_test

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"path/filepath"

	"go.nhat.io/cookiejar"
)

func ExampleNewPersistentJar() {
	tempDir, err := os.MkdirTemp(os.TempDir(), "example")
	if err != nil {
		log.Fatal(err)
	}

	defer os.RemoveAll(tempDir)

	cookiesFile := filepath.Join(tempDir, "cookies")

	// Start a server to give us cookies.
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if cookie, err := r.Cookie("Flavor"); err != nil {
			http.SetCookie(w, &http.Cookie{Name: "Flavor", Value: "Chocolate Chip"})
		} else {
			cookie.Value = "Oatmeal Raisin"
			http.SetCookie(w, cookie)
		}
	}))
	defer ts.Close()

	u, err := url.Parse(ts.URL)
	if err != nil {
		log.Fatal(err)
	}

	jar := cookiejar.NewPersistentJar(
		cookiejar.WithFilePath(cookiesFile),
		cookiejar.WithAutoSync(true),
		// All users of cookiejar should import "golang.org/x/net/publicsuffix"
		cookiejar.WithPublicSuffixList(publicsuffix.List),
	)

	client := &http.Client{
		Jar: jar,
	}

	if _, err = client.Get(u.String()); err != nil {
		log.Fatal(err)
	}

	fmt.Println("After 1st request:")
	for _, cookie := range jar.Cookies(u) {
		fmt.Printf("  %s: %s\n", cookie.Name, cookie.Value)
	}

	if _, err = client.Get(u.String()); err != nil {
		log.Fatal(err)
	}

	fmt.Println("After 2nd request:")
	for _, cookie := range jar.Cookies(u) {
		fmt.Printf("  %s: %s\n", cookie.Name, cookie.Value)
	}

	// Output:
	// After 1st request:
	//   Flavor: Chocolate Chip
	// After 2nd request:
	//   Flavor: Oatmeal Raisin
}

Donation

If this project help you reduce time to develop, you can give me a cup of coffee :)

Paypal donation

paypal

       or scan this

Documentation

Overview

Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Entry

type Entry struct {
	Name       string
	Value      string
	Quoted     bool
	Domain     string
	Path       string
	SameSite   string
	Secure     bool
	HttpOnly   bool
	Persistent bool
	HostOnly   bool
	Expires    time.Time
	Creation   time.Time
	LastAccess time.Time
	SeqNum     uint64
}

Entry is a public presentation of the entry struct.

type EntrySerDer

type EntrySerDer interface {
	Serialize(w io.Writer, entries map[string]map[string]Entry) error
	Deserialize(r io.Reader) (map[string]map[string]Entry, error)
}

EntrySerDer is an interface for serializing and deserializing entries.

type Jar

type Jar struct {
	// contains filtered or unexported fields
}

Jar implements the http.CookieJar interface from the net/http package.

func New

func New(o *Options) (*Jar, error)

New returns a new cookie jar. A nil *Options is equivalent to a zero Options.

Example
// Start a server to give us cookies.
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	if cookie, err := r.Cookie("Flavor"); err != nil {
		http.SetCookie(w, &http.Cookie{Name: "Flavor", Value: "Chocolate Chip"})
	} else {
		cookie.Value = "Oatmeal Raisin"
		http.SetCookie(w, cookie)
	}
}))
defer ts.Close()

u, err := url.Parse(ts.URL)
if err != nil {
	log.Fatal(err)
}

// All users of cookiejar should import "golang.org/x/net/publicsuffix"
jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
if err != nil {
	log.Fatal(err)
}

client := &http.Client{
	Jar: jar,
}

if _, err = client.Get(u.String()); err != nil {
	log.Fatal(err)
}

fmt.Println("After 1st request:")
for _, cookie := range jar.Cookies(u) {
	fmt.Printf("  %s: %s\n", cookie.Name, cookie.Value)
}

if _, err = client.Get(u.String()); err != nil {
	log.Fatal(err)
}

fmt.Println("After 2nd request:")
for _, cookie := range jar.Cookies(u) {
	fmt.Printf("  %s: %s\n", cookie.Name, cookie.Value)
}
Output:

After 1st request:
  Flavor: Chocolate Chip
After 2nd request:
  Flavor: Oatmeal Raisin

func (*Jar) Cookies

func (j *Jar) Cookies(u *url.URL) (cookies []*http.Cookie)

Cookies implements the Cookies method of the http.CookieJar interface.

It returns an empty slice if the URL's scheme is not HTTP or HTTPS.

func (*Jar) SetCookies

func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie)

SetCookies implements the SetCookies method of the http.CookieJar interface.

It does nothing if the URL's scheme is not HTTP or HTTPS.

type Options

type Options struct {
	// PublicSuffixList is the public suffix list that determines whether
	// an HTTP server can set a cookie for a domain.
	//
	// A nil value is valid and may be useful for testing but it is not
	// secure: it means that the HTTP server for foo.co.uk can set a cookie
	// for bar.co.uk.
	PublicSuffixList PublicSuffixList
}

Options are the options for creating a new Jar.

type PersistentJar

type PersistentJar struct {
	// contains filtered or unexported fields
}

PersistentJar persists cookies to a file.

func NewPersistentJar

func NewPersistentJar(opts ...PersistentJarOption) *PersistentJar

NewPersistentJar creates new persistent cookie jar.

Example
tempDir, err := os.MkdirTemp(os.TempDir(), "example")
if err != nil {
	log.Fatal(err)
}

defer os.RemoveAll(tempDir)

cookiesFile := filepath.Join(tempDir, "cookies")

// Start a server to give us cookies.
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	if cookie, err := r.Cookie("Flavor"); err != nil {
		http.SetCookie(w, &http.Cookie{Name: "Flavor", Value: "Chocolate Chip"})
	} else {
		cookie.Value = "Oatmeal Raisin"
		http.SetCookie(w, cookie)
	}
}))
defer ts.Close()

u, err := url.Parse(ts.URL)
if err != nil {
	log.Fatal(err)
}

jar := cookiejar.NewPersistentJar(
	cookiejar.WithFilePath(cookiesFile),
	cookiejar.WithAutoSync(true),
	// All users of cookiejar should import "golang.org/x/net/publicsuffix"
	cookiejar.WithPublicSuffixList(publicsuffix.List),
)

client := &http.Client{
	Jar: jar,
}

if _, err = client.Get(u.String()); err != nil {
	log.Fatal(err)
}

fmt.Println("After 1st request:")
for _, cookie := range jar.Cookies(u) {
	fmt.Printf("  %s: %s\n", cookie.Name, cookie.Value)
}

if _, err = client.Get(u.String()); err != nil {
	log.Fatal(err)
}

fmt.Println("After 2nd request:")
for _, cookie := range jar.Cookies(u) {
	fmt.Printf("  %s: %s\n", cookie.Name, cookie.Value)
}
Output:

After 1st request:
  Flavor: Chocolate Chip
After 2nd request:
  Flavor: Oatmeal Raisin

func (*PersistentJar) Cookies

func (j *PersistentJar) Cookies(u *url.URL) []*http.Cookie

Cookies implements the Cookies method of the http.CookieJar interface.

It returns an empty slice if the URL's scheme is not HTTP or HTTPS.

func (*PersistentJar) SetCookies

func (j *PersistentJar) SetCookies(u *url.URL, cookies []*http.Cookie)

SetCookies implements the SetCookies method of the http.CookieJar interface.

It does nothing if the URL's scheme is not HTTP or HTTPS.

func (*PersistentJar) Sync

func (j *PersistentJar) Sync() error

Sync persists cookies to the file.

type PersistentJarOption

type PersistentJarOption interface {
	// contains filtered or unexported methods
}

PersistentJarOption is an option to configure PersistentJar.

func WithAutoSync

func WithAutoSync(autoSync bool) PersistentJarOption

WithAutoSync sets the auto sync mode.

func WithFilePath

func WithFilePath(filePath string) PersistentJarOption

WithFilePath sets the file path.

func WithFilePerm

func WithFilePerm(filePerm os.FileMode) PersistentJarOption

WithFilePerm sets the file permission.

func WithFs

func WithFs(fs afero.Fs) PersistentJarOption

WithFs sets the file system.

func WithLogger

func WithLogger(logger ctxd.Logger) PersistentJarOption

WithLogger sets the logger.

func WithPublicSuffixList

func WithPublicSuffixList(list PublicSuffixList) PersistentJarOption

WithPublicSuffixList sets the public suffix list.

func WithSerDer

func WithSerDer(serder EntrySerDer) PersistentJarOption

WithSerDer sets the serializer/deserializer.

type PublicSuffixList

type PublicSuffixList interface {
	// PublicSuffix returns the public suffix of domain.
	//
	// TODO: specify which of the caller and callee is responsible for IP
	// addresses, for leading and trailing dots, for case sensitivity, and
	// for IDN/Punycode.
	PublicSuffix(domain string) string

	// String returns a description of the source of this public suffix
	// list. The description will typically contain something like a time
	// stamp or version number.
	String() string
}

PublicSuffixList provides the public suffix of a domain. For example:

  • the public suffix of "example.com" is "com",
  • the public suffix of "foo1.foo2.foo3.co.uk" is "co.uk", and
  • the public suffix of "bar.pvt.k12.ma.us" is "pvt.k12.ma.us".

Implementations of PublicSuffixList must be safe for concurrent use by multiple goroutines.

An implementation that always returns "" is valid and may be useful for testing but it is not secure: it means that the HTTP server for foo.com can set a cookie for bar.com.

A public suffix list implementation is in the package golang.org/x/net/publicsuffix.

Directories

Path Synopsis
internal
Package mock provides mocks for the cookiejar package.
Package mock provides mocks for the cookiejar package.

Jump to

Keyboard shortcuts

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