ironsession

package module
v0.0.0-...-7838ce1 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

README

Iron Session for Go

A secure, encrypted session implementation for Go, inspired by the Node.js iron-session package.

Features

  • Encrypted sessions: All session data is encrypted using AES-GCM
  • Integrity protection: HMAC-SHA256 ensures data hasn't been tampered with
  • Secure defaults: HttpOnly, Secure, and SameSite cookies by default
  • PBKDF2 key derivation: Protection against brute force attacks
  • Context integration: Easy access to sessions in HTTP handlers
  • Middleware support: Drop-in session handling for HTTP servers

Installation

go get github.com/sh4nnongoh/ironsession

Quick Start

package main

import (
    "fmt"
    "net/http"
    
    "github.com/sh4nnongoh/ironsession"
)

func main() {
    // Configure session
    opts := ironsession.DefaultOptions().
        WithPassword("your-very-long-secure-password-here").
        WithCookieName("myapp_session").
        WithTTL(86400) // 24 hours

    // Create session manager
    is, err := ironsession.New(opts)
    if err != nil {
        panic(err)
    }

    // Use middleware
    http.Handle("/", is.Middleware(http.HandlerFunc(handler)))
    
    http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
    // Get session from context
    session, ok := ironsession.GetSessionFromContext(r.Context())
    if !ok {
        http.Error(w, "Session not found", http.StatusInternalServerError)
        return
    }

    // Use session
    count, _ := session.Get("count").(int)
    count++
    session.Set("count", count)

    fmt.Fprintf(w, "Visit count: %d", count)
}

Testing

go test ./...
go test -v ./...

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidSession       = fmt.Errorf("invalid session")
	ErrDecryptionFailed     = fmt.Errorf("decryption failed")
	ErrIntegrityCheckFailed = fmt.Errorf("integrity check failed")
	ErrSessionExpired       = fmt.Errorf("session expired")
	ErrInvalidOptions       = fmt.Errorf("invalid options")
)

Functions

This section is empty.

Types

type IronSession

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

func New

func New(opts *Options) (*IronSession, error)

func (*IronSession) DecodeSession

func (is *IronSession) DecodeSession(encrypted string, name string) (*Session, error)

func (*IronSession) EncodeSession

func (is *IronSession) EncodeSession(session *Session) (string, error)

func (*IronSession) GetSession

func (is *IronSession) GetSession(r *http.Request, name string) (*Session, error)

func (*IronSession) Middleware

func (is *IronSession) Middleware(next http.Handler) http.Handler

func (*IronSession) NewSession

func (is *IronSession) NewSession(name string) *Session

func (*IronSession) Save

func (is *IronSession) Save(session *Session, w http.ResponseWriter) error

type Options

type Options struct {
	// Required: Password for encryption (min 32 chars recommended)
	Password string

	// Optional: Salt for key derivation (auto-generated if empty)
	Salt string

	// Optional: Cookie name (default: "ironsession")
	CookieName string

	// Optional: Time to live in seconds (default: 86400 = 24 hours)
	TTL int

	// Optional: Cookie path (default: "/")
	Path string

	// Optional: Cookie domain
	Domain string

	// Optional: Secure flag (HTTPS only) (default: true in production)
	Secure bool

	// Optional: HttpOnly flag (default: true)
	HttpOnly bool

	// Optional: SameSite policy (default: http.SameSiteLaxMode)
	SameSite http.SameSite

	// Optional: MaxAge for cookie (overrides TTL)
	MaxAge int

	// Optional: PBKDF2 iterations (default: 10000)
	Iterations int

	// Optional: Hash function for PBKDF2 (default: sha256.New)
	HashFunc func() hash.Hash

	// Optional: Cipher function (default: aes.NewCipher)
	CipherFunc func(key []byte) (cipher.Block, error)
}

Options holds configuration for IronSession

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns sensible default options

func (*Options) Validate

func (o *Options) Validate() error

Validate checks if options are valid

func (*Options) WithCipherFunc

func (o *Options) WithCipherFunc(cipherFunc func(key []byte) (cipher.Block, error)) *Options

WithCipherFunc sets the cipher function

func (*Options) WithCookieName

func (o *Options) WithCookieName(name string) *Options

WithCookieName sets the cookie name

func (*Options) WithHashFunc

func (o *Options) WithHashFunc(hashFunc func() hash.Hash) *Options

WithHashFunc sets the hash function

func (*Options) WithHttpOnly

func (o *Options) WithHttpOnly(httpOnly bool) *Options

WithHttpOnly sets the HttpOnly flag

func (*Options) WithIterations

func (o *Options) WithIterations(iterations int) *Options

WithIterations sets the PBKDF2 iterations

func (*Options) WithPassword

func (o *Options) WithPassword(password string) *Options

WithPassword sets the password and returns Options for chaining

func (*Options) WithSameSite

func (o *Options) WithSameSite(sameSite http.SameSite) *Options

WithSameSite sets the SameSite policy

func (*Options) WithSecure

func (o *Options) WithSecure(secure bool) *Options

WithSecure sets the secure flag

func (*Options) WithTTL

func (o *Options) WithTTL(ttl int) *Options

WithTTL sets the time to live

type Session

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

func GetSessionFromContext

func GetSessionFromContext(ctx context.Context) (*Session, bool)

func (*Session) Clear

func (s *Session) Clear()

func (*Session) Data

func (s *Session) Data() map[string]interface{}

func (*Session) Delete

func (s *Session) Delete(key string)

func (*Session) Destroy

func (s *Session) Destroy(w http.ResponseWriter)

func (*Session) Get

func (s *Session) Get(key string) interface{}

func (*Session) Has

func (s *Session) Has(key string) bool

func (*Session) Keys

func (s *Session) Keys() []string

func (*Session) Save

func (s *Session) Save(is *IronSession, w http.ResponseWriter) error

func (*Session) Set

func (s *Session) Set(key string, value interface{})

type SessionError

type SessionError struct {
	Op  string
	Err error
	Msg string
}

func NewSessionError

func NewSessionError(op string, err error, msg string) *SessionError

func (*SessionError) Error

func (e *SessionError) Error() string

func (*SessionError) Unwrap

func (e *SessionError) Unwrap() error

Jump to

Keyboard shortcuts

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