session

package module
v3.1.9 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2022 License: MIT Imports: 16 Imported by: 1

README

session

A efficient, safely and easy-to-use session library for Go.

Build Codecov ReportCard GoDoc License

Quick Start

Download and install
go get -v github.com/Scumfunk/session/v3
Create file server.go
package main

import (
	"context"
	"fmt"
	"net/http"

	session "github.com/Scumfunk/session/v3"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		store, err := session.Start(context.Background(), w, r)
		if err != nil {
			fmt.Fprint(w, err)
			return
		}

		store.Set("foo", "bar")
		err = store.Save()
		if err != nil {
			fmt.Fprint(w, err)
			return
		}

		http.Redirect(w, r, "/foo", 302)
	})

	http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
		store, err := session.Start(context.Background(), w, r)
		if err != nil {
			fmt.Fprint(w, err)
			return
		}

		foo, ok := store.Get("foo")
		if ok {
			fmt.Fprintf(w, "foo:%s", foo)
			return
		}
		fmt.Fprint(w, "does not exist")
	})

	http.ListenAndServe(":8080", nil)
}
Build and run
go build server.go
./server
Open in your web browser

http://localhost:8080

    foo:bar

Features

  • Easy to use
  • Multi-storage support
  • Multi-middleware support
  • More secure, signature-based tamper-proof
  • Context support
  • Support request header and query parameters

Store Implementations

Middlewares

MIT License

Copyright (c) 2021 Lyric

Documentation

Overview

Package session implements a efficient, safely and easy-to-use session library for Go.

Example:

package main

import (
	"context"
	"fmt"
	"net/http"

	session "github.com/Scumfunk/session/v3"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		store, err := session.Start(context.Background(), w, r)
		if err != nil {
			fmt.Fprint(w, err)
			return
		}

		store.Set("foo", "bar")
		err = store.Save()
		if err != nil {
			fmt.Fprint(w, err)
			return
		}

		http.Redirect(w, r, "/foo", 302)
	})

	http.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
		store, err := session.Start(context.Background(), w, r)
		if err != nil {
			fmt.Fprint(w, err)
			return
		}

		foo, ok := store.Get("foo")
		if ok {
			fmt.Fprintf(w, "foo:%s", foo)
			return
		}
		fmt.Fprint(w, "does not exist")
	})

	http.ListenAndServe(":8080", nil)
}

Open in your web browser at http://localhost:8080

Output:

foo:bar

Learn more at https://github.com/go-session/session

Index

Constants

View Source
const Version = "3.1.9"

Version # of session

Variables

View Source
var (
	// ErrInvalidSessionID invalid session id
	ErrInvalidSessionID = errors.New("invalid session id")
)

Functions

func Destroy

func Destroy(ctx context.Context, w http.ResponseWriter, r *http.Request) error

Destroy a session

func FromReqContext

func FromReqContext(ctx context.Context) (*http.Request, bool)

FromReqContext returns the Request value stored in ctx, if any.

func FromResContext

func FromResContext(ctx context.Context) (http.ResponseWriter, bool)

FromResContext returns the ResponseWriter value stored in ctx, if any.

func InitManager

func InitManager(opt ...Option)

InitManager initialize the global session management instance

Types

type IDHandlerFunc

type IDHandlerFunc func(context.Context) string

IDHandlerFunc Define the handler to get the session id

type Manager

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

Manager A session management instance, including start and destroy operations

func NewManager

func NewManager(opt ...Option) *Manager

NewManager Create a session management instance

func (*Manager) Destroy

func (m *Manager) Destroy(ctx context.Context, w http.ResponseWriter, r *http.Request) error

Destroy a session

func (*Manager) Refresh

func (m *Manager) Refresh(ctx context.Context, w http.ResponseWriter, r *http.Request) (Store, error)

Refresh a session and return to session storage

func (*Manager) Start

func (m *Manager) Start(ctx context.Context, w http.ResponseWriter, r *http.Request) (Store, error)

Start a session and return to session storage

type ManagerStore

type ManagerStore interface {
	// Check the session store exists
	Check(ctx context.Context, sid string) (bool, error)
	// Create a session store and specify the expiration time (in seconds)
	Create(ctx context.Context, sid string, expired int64) (Store, error)
	// Update a session store and specify the expiration time (in seconds)
	Update(ctx context.Context, sid string, expired int64) (Store, error)
	// Delete a session store
	Delete(ctx context.Context, sid string) error
	// Use sid to replace old sid and return session store
	Refresh(ctx context.Context, oldsid, sid string, expired int64) (Store, error)
	// Close storage, release resources
	Close() error
}

ManagerStore Management of session storage, including creation, update, and delete operations

func NewMemoryStore

func NewMemoryStore() ManagerStore

NewMemoryStore create an instance of a memory store

type Option

type Option func(*options)

Option A session parameter options

func SetCookieLifeTime

func SetCookieLifeTime(cookieLifeTime int) Option

SetCookieLifeTime Set the cookie expiration time (in seconds)

func SetCookieName

func SetCookieName(cookieName string) Option

SetCookieName Set the cookie name

func SetDomain

func SetDomain(domain string) Option

SetDomain Set the domain name of the cookie

func SetEnableSIDInHTTPHeader

func SetEnableSIDInHTTPHeader(enableSIDInHTTPHeader bool) Option

SetEnableSIDInHTTPHeader Allow session id to be obtained from the request header

func SetEnableSIDInURLQuery

func SetEnableSIDInURLQuery(enableSIDInURLQuery bool) Option

SetEnableSIDInURLQuery Allow session id from URL query parameters (enabled by default)

func SetEnableSetCookie

func SetEnableSetCookie(enableSetCookie bool) Option

SetEnableSetCookie Enable writing session id to cookie (enabled by default, can be turned off if no cookie is written)

func SetExpired

func SetExpired(expired int64) Option

SetExpired Set session expiration time (in seconds)

func SetForceSecure

func SetForceSecure(forceSecure bool) Option

SetForceSecure Set cookie security (force)

func SetSameSite

func SetSameSite(sameSite http.SameSite) Option

SetSameSite Set SameSite attribute of the cookie

func SetSecure

func SetSecure(secure bool) Option

SetSecure Set cookie security

func SetSessionID

func SetSessionID(handler IDHandlerFunc) Option

SetSessionID Set callback function to generate session id

func SetSessionNameInHTTPHeader

func SetSessionNameInHTTPHeader(sessionNameInHTTPHeader string) Option

SetSessionNameInHTTPHeader The key name in the request header where the session ID is stored (if it is empty, the default is the cookie name)

func SetSign

func SetSign(sign []byte) Option

SetSign Set the session id signature value

func SetStore

func SetStore(store ManagerStore) Option

SetStore Set session management storage

type Store

type Store interface {
	// Get a session storage context
	Context() context.Context
	// Get the current session id
	SessionID() string
	// Set session value, call save function to take effect
	Set(key string, value interface{})
	// Get session value
	Get(key string) (interface{}, bool)
	// Delete session value, call save function to take effect
	Delete(key string) interface{}
	// Save session data
	Save() error
	// Clear all session data
	Flush() error
}

Store A session id storage operation

func Refresh

func Refresh(ctx context.Context, w http.ResponseWriter, r *http.Request) (Store, error)

Refresh a session and return to session storage

func Start

Start a session and return to session storage

Jump to

Keyboard shortcuts

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