cookie

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package cookie parses and serializes HTTP cookie headers, a port of the npm "cookie" package that Express and cookie-parser use to read the Cookie request header and to build Set-Cookie response headers. It exposes Parse to turn a raw "Cookie" header into a map of names to values and Serialize to render a single name/value pair plus its attributes into a Set-Cookie value, using only the Go standard library.

You reach for this package on both sides of the request/response cycle. On the way in, Parse gives you the individual cookies a client sent so a handler can look up a session id or a preference flag without string-splitting the header itself. On the way out, Serialize produces a well-formed Set-Cookie value with Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite attributes, so you can issue login cookies, clear a cookie by expiring it, or scope a cookie to a path without hand-assembling the syntax and risking a malformed header.

Values are transported using JavaScript's encodeURIComponent conventions. Serialize percent-encodes every byte of the value that is not an encodeURIComponent-safe character (letters, digits, and the set -_.!~*'()), which keeps semicolons, commas, spaces, and other separators from corrupting the header. Parse reverses this: it URL-decodes each value, tolerating values that were never encoded, and additionally strips one layer of surrounding double quotes so quoted-string cookie values round-trip. When the same cookie name appears more than once in a header the first occurrence wins, matching the npm package, and pairs with an empty name or no '=' are skipped.

Serialize validates its inputs rather than emitting a header that a client would reject. The name must be an RFC 6265 token and the encoded value must be a valid cookie-octet sequence, otherwise an error is returned; Path and Domain must be valid field-content. Max-Age follows net/http conventions rather than dotenv-style literalism: a positive value sets Max-Age to that many seconds, a negative value emits "Max-Age=0" to delete the cookie immediately, and zero omits the attribute entirely. A zero Expires time omits Expires, and an empty SameSite omits SameSite while "Lax", "Strict", and "None" (case-insensitive) are accepted and anything else is an error. Passing a nil *Options serializes just the name and value with no attributes.

Parity with the Node original is close for everyday cookie handling: the encodeURIComponent-based value codec, the token and cookie-octet validation, the first-wins duplicate rule, and the attribute names and formats all match. The deliberate differences are idiomatic Go ones. Attributes are supplied through a typed Options struct instead of a plain JavaScript object, the value codec is fixed to encode/decode rather than accepting caller-supplied encode/decode callbacks, Serialize returns an explicit error instead of throwing a TypeError, and Max-Age is interpreted with net/http's sign conventions so it composes naturally with the rest of the standard library.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse(header string) map[string]string

Parse parses a Cookie header (for example "a=1; b=2") into a map of names to values. Values are URL-decoded. When a name appears more than once, the first occurrence wins.

Example

ExampleParse turns a raw Cookie request header into a map of names to values. Each value is URL-decoded, reversing the encoding that Serialize applies, so "a%20b%2Bc" decodes back to "a b+c". When a name appears more than once the first occurrence wins. Here two cookies are parsed out of a single header string.

package main

import (
	"fmt"

	"github.com/malcolmston/express/cookie"
)

func main() {
	m := cookie.Parse("sid=a%20b%2Bc; theme=dark")
	fmt.Printf("%q %q\n", m["sid"], m["theme"])
}
Output:
"a b+c" "dark"

func Serialize

func Serialize(name, value string, opts *Options) (string, error)

Serialize builds a Set-Cookie header value for the given name and value, applying the attributes in opts (which may be nil). The value is URL-encoded. It returns an error if the name or value contains invalid characters, or if an attribute value is invalid.

Example

ExampleSerialize builds a Set-Cookie header value from a name, a value, and a set of attributes. The value is percent-encoded using encodeURIComponent conventions, so the space and '+' in "a b+c" become "%20" and "%2B". The Options fields add Path, Max-Age, and HttpOnly attributes in the canonical order. This is the header a server sends to store a cookie in the client.

package main

import (
	"fmt"

	"github.com/malcolmston/express/cookie"
)

func main() {
	s, err := cookie.Serialize("sid", "a b+c", &cookie.Options{
		Path:     "/",
		MaxAge:   3600,
		HttpOnly: true,
	})
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(s)
}
Output:
sid=a%20b%2Bc; Path=/; Max-Age=3600; HttpOnly

Types

type Options

type Options struct {
	// Path sets the Path attribute.
	Path string
	// Domain sets the Domain attribute.
	Domain string
	// Expires sets the Expires attribute. A zero time omits the attribute.
	Expires time.Time
	// MaxAge sets the Max-Age attribute. Following net/http conventions:
	// a positive value sets Max-Age to that number of seconds, a negative
	// value sets Max-Age=0 (delete now), and zero omits the attribute.
	MaxAge int
	// Secure sets the Secure attribute.
	Secure bool
	// HttpOnly sets the HttpOnly attribute.
	HttpOnly bool
	// SameSite sets the SameSite attribute; recognized values are "Lax",
	// "Strict", and "None" (case-insensitive). An empty value omits it.
	SameSite string
}

Options holds the attributes used when serializing a cookie.

Jump to

Keyboard shortcuts

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