Categorygo.nhat.io/cookiejar
modulepackage
0.2.0
Repository: https://github.com/nhatthm/go-cookiejar.git
Documentation: pkg.go.dev

# 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:

OptionDescriptionDefault Value
WithFilePathThe path to the file to store the cookies"cookies.json"
WithFilePermThe file permission to use for persisting the cookies0600
WithAutoSyncWhether to automatically sync the cookies to the file after each requestfalse
WithLoggerThe logger to use for loggingNo log
WithFsThe filesystem to use for persisting the cookiesafero.NewOsFs()
WithSerDerThe serializer/deserializer to use for persisting the cookiesjson
WithPublicSuffixListThe 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

# Packages

Package mock provides mocks for the cookiejar package.

# Functions

New returns a new cookie jar.
NewPersistentJar creates new persistent cookie jar.
WithAutoSync sets the auto sync mode.
WithFilePath sets the file path.
WithFilePerm sets the file permission.
WithFs sets the file system.
WithLogger sets the logger.
WithPublicSuffixList sets the public suffix list.
WithSerDer sets the serializer/deserializer.

# Structs

Entry
Entry is a public presentation of the entry struct.
Jar implements the http.CookieJar interface from the net/http package.
Options are the options for creating a new Jar.
PersistentJar persists cookies to a file.

# Interfaces

EntrySerDer is an interface for serializing and deserializing entries.
PersistentJarOption is an option to configure PersistentJar.
PublicSuffixList provides the public suffix of a domain.