cookiejar

package module
v0.0.0-...-6728cad Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2026 License: BSD-3-Clause Imports: 17 Imported by: 0

README

cookiejar

juju/persistent-cookiejar库不同的地方:

  • 移除了cookie保存到文件的功能.
  • 增加了序列化和反序列化到json/gob.

提供序列化和反序列能力, 如何存储这些数据交给调用方. 序列化的cookie会包含那些无过期时间的cookie.

示例

func TestJar_MarshalJSON(t *testing.T) {
	jar, err := New(nil)
	require.NoError(t, err)
	{
		// --- Mock 域名 A (Google) ---
		u1, _ := url.Parse("https://google.com")
		cookies1 := []*http.Cookie{
			{Name: "SID", Value: "google_session_id", Domain: ".google.com", Path: "/"},
		}
		jar.SetCookies(u1, cookies1)

		// --- Mock 域名 B (GitHub) ---
		u2, _ := url.Parse("https://github.com")
		cookies2 := []*http.Cookie{
			{Name: "logged_in", Value: "yes", Domain: ".github.com", Path: "/"},
			{Name: "user_session", Value: "gh_tok_12345", Domain: ".github.com", Path: "/"},
		}
		jar.SetCookies(u2, cookies2)

		// --- Mock 域名 C (Baidu) ---
		u3, _ := url.Parse("https://baidu.com")
		cookies3 := []*http.Cookie{
			{Name: "BDUSS", Value: "baidu_token_xyz", Domain: ".baidu.com", Path: "/"},
		}
		jar.SetCookies(u3, cookies3)
	}
	ret, err := json.Marshal(jar)
	require.NoError(t, err)
	t.Log(string(ret))
}

func TestJar_UnmarshalJSON(t *testing.T) {
	const jsonData = `[{"Name":"BDUSS","Value":"baidu_token_xyz","Domain":"baidu.com","Path":"/","Secure":false,"HttpOnly":false,"Persistent":false,"HostOnly":false,"Expires":"9999-12-31T23:59:59Z","Creation":"2026-01-31T23:45:49.5613454+08:00","LastAccess":"2026-01-31T23:45:49.5613454+08:00","Updated":"2026-01-31T23:45:49.5613454+08:00","CanonicalHost":"baidu.com"},{"Name":"logged_in","Value":"yes","Domain":"github.com","Path":"/","Secure":false,"HttpOnly":false,"Persistent":false,"HostOnly":false,"Expires":"9999-12-31T23:59:59Z","Creation":"2026-01-31T23:45:49.5613454+08:00","LastAccess":"2026-01-31T23:45:49.5613454+08:00","Updated":"2026-01-31T23:45:49.5613454+08:00","CanonicalHost":"github.com"},{"Name":"user_session","Value":"gh_tok_12345","Domain":"github.com","Path":"/","Secure":false,"HttpOnly":false,"Persistent":false,"HostOnly":false,"Expires":"9999-12-31T23:59:59Z","Creation":"2026-01-31T23:45:49.5613454+08:00","LastAccess":"2026-01-31T23:45:49.5613454+08:00","Updated":"2026-01-31T23:45:49.5613454+08:00","CanonicalHost":"github.com"},{"Name":"SID","Value":"google_session_id","Domain":"google.com","Path":"/","Secure":false,"HttpOnly":false,"Persistent":false,"HostOnly":false,"Expires":"9999-12-31T23:59:59Z","Creation":"2026-01-31T23:45:49.5613454+08:00","LastAccess":"2026-01-31T23:45:49.5613454+08:00","Updated":"2026-01-31T23:45:49.5613454+08:00","CanonicalHost":"google.com"}]`
	jar, err := New(nil)
	require.NoError(t, err)
	err = json.Unmarshal([]byte(jsonData), jar)
	require.NoError(t, err)
	for _, cookie := range jar.AllCookies() {
		t.Log(cookie)
	}
}

func TestJar_GobEncode(t *testing.T) {
	jar, err := New(nil)
	require.NoError(t, err)
	{
		// --- Mock 域名 A (Google) ---
		u1, _ := url.Parse("https://google.com")
		cookies1 := []*http.Cookie{
			{Name: "SID", Value: "google_session_id", Domain: ".google.com", Path: "/"},
		}
		jar.SetCookies(u1, cookies1)

		// --- Mock 域名 B (GitHub) ---
		u2, _ := url.Parse("https://github.com")
		cookies2 := []*http.Cookie{
			{Name: "logged_in", Value: "yes", Domain: ".github.com", Path: "/"},
			{Name: "user_session", Value: "gh_tok_12345", Domain: ".github.com", Path: "/"},
		}
		jar.SetCookies(u2, cookies2)

		// --- Mock 域名 C (Baidu) ---
		u3, _ := url.Parse("https://baidu.com")
		cookies3 := []*http.Cookie{
			{Name: "BDUSS", Value: "baidu_token_xyz", Domain: ".baidu.com", Path: "/"},
		}
		jar.SetCookies(u3, cookies3)
	}
	buf := new(bytes.Buffer)
	encoder := gob.NewEncoder(buf)
	err = encoder.Encode(jar)
	require.NoError(t, err)
	t.Log(base64.StdEncoding.EncodeToString(buf.Bytes()))
}

func TestJar_GobDecode(t *testing.T) {
	const gobBase64Data = `CX8FAQL/ggAAAP4CwP+AAP4Cug3/hwIBAv+IAAH/hAAA/7j/gwMBAQVlbnRyeQH/hAABDQEETmFtZQEMAAEFVmFsdWUBDAABBkRvbWFpbgEMAAEEUGF0aAEMAAEGU2VjdXJlAQIAAQhIdHRwT25seQECAAEKUGVyc2lzdGVudAECAAEISG9zdE9ubHkBAgABB0V4cGlyZXMB/4YAAQhDcmVhdGlvbgH/hgABCkxhc3RBY2Nlc3MB/4YAAQdVcGRhdGVkAf+GAAENQ2Fub25pY2FsSG9zdAEMAAAAEP+FBQEBBFRpbWUB/4YAAAD+Ad7/iAAEAQVCRFVTUwEPYmFpZHVfdG9rZW5feHl6AQliYWlkdS5jb20BAS8FDwEAAABJd4Y4fwAAAAD//wEPAQAAAA7hEByANerCQAHgAQ8BAAAADuEQHIA16sJAAeABDwEAAAAO4RAcgDXqwkAB4AEJYmFpZHUuY29tAAEJbG9nZ2VkX2luAQN5ZXMBCmdpdGh1Yi5jb20BAS8FDwEAAABJd4Y4fwAAAAD//wEPAQAAAA7hEByANerCQAHgAQ8BAAAADuEQHIA16sJAAeABDwEAAAAO4RAcgDXqwkAB4AEKZ2l0aHViLmNvbQABDHVzZXJfc2Vzc2lvbgEMZ2hfdG9rXzEyMzQ1AQpnaXRodWIuY29tAQEvBQ8BAAAASXeGOH8AAAAA//8BDwEAAAAO4RAcgDXqwkAB4AEPAQAAAA7hEByANerCQAHgAQ8BAAAADuEQHIA16sJAAeABCmdpdGh1Yi5jb20AAQNTSUQBEWdvb2dsZV9zZXNzaW9uX2lkAQpnb29nbGUuY29tAQEvBQ8BAAAASXeGOH8AAAAA//8BDwEAAAAO4RAcgDXqwkAB4AEPAQAAAA7hEByANerCQAHgAQ8BAAAADuEQHIA16sJAAeABCmdvb2dsZS5jb20A`
	jar, err := New(nil)
	require.NoError(t, err)
	gobData, err := base64.StdEncoding.DecodeString(gobBase64Data)
	require.NoError(t, err)
	decoder := gob.NewDecoder(bytes.NewReader(gobData))
	err = decoder.Decode(jar)
	require.NoError(t, err)
	for _, cookie := range jar.AllCookies() {
		t.Log(cookie)
	}
}

Documentation

Overview

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

This implementation is a fork of net/http/cookiejar which also implements methods for dumping the cookies to persistent storage and retrieving them.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

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.

New will return an error if the cookies could not be loaded from the file for any reason than if the file does not exist.

func (*Jar) AllCookies

func (j *Jar) AllCookies() (cookies []*http.Cookie)

AllCookies returns all cookies in the jar. The returned cookies will have Domain, Expires, HttpOnly, Name, Secure, Path, and Value filled out. Expired cookies will not be returned. This function does not modify the cookie jar.

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) GobDecode

func (j *Jar) GobDecode(p []byte) error

GobDecode 解组行为并不会完全重写Jar中的cookie, 它是将传入的cookie与当前的Jar中的cookie进行合并.

func (*Jar) GobEncode

func (j *Jar) GobEncode() ([]byte, error)

func (*Jar) MarshalJSON

func (j *Jar) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler by encoding all cookies currently in the jar.

func (*Jar) RemoveAll

func (j *Jar) RemoveAll()

RemoveAll removes all the cookies from the jar.

func (*Jar) RemoveAllHost

func (j *Jar) RemoveAllHost(host string)

RemoveAllHost removes any cookies from the jar that were set for the given host.

func (*Jar) RemoveCookie

func (j *Jar) RemoveCookie(c *http.Cookie)

RemoveCookie removes the cookie matching the name, domain and path specified by c.

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.

func (*Jar) UnmarshalJSON

func (j *Jar) UnmarshalJSON(p []byte) error

UnmarshalJSON 解组行为并不会完全重写Jar中的cookie, 它是将传入的cookie与当前的Jar中的cookie进行合并.

type Options

type Options struct {
	// PublicSuffixList is the public suffix list that determines whether
	// an HTTP server can set a cookie for a domain.
	//
	// If this is nil, the public suffix list implementation in golang.org/x/net/publicsuffix
	// is used.
	PublicSuffixList PublicSuffixList
}

Options are the options for creating a new Jar.

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.

Jump to

Keyboard shortcuts

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