gsession

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2019 License: MIT Imports: 10 Imported by: 0

README

gsession

Very simple Go session management library. Provides memory and filesystem stores.

Features

  • Absolute expiry, regardless of session activity
  • Idle inactivity timeout
  • Renewal timeout when session ID is renewed regardless of the session activity or idle timeout
  • Expiry, idle and renew timeouts can be disabled
  • Uses excellent Badger KV DB for on disk persistance

Install

go get -u github.com/anhuret/gsession

Go version

Built and tested with Go 1.11.4

Usage


package main

import (
	gs "github.com/anhuret/gsession"
	"net/http"
)

func main() {
	// Create default session manager
	// Use nil to get default memory store
	// Use 0 for expiry, idle and renew to get defaults: 24H, 1H and 30M respectively
	manager := gs.New(nil, 0, 0, 0)

	// Handler function
	sayHello := func(w http.ResponseWriter, r *http.Request) {
		switch r.RequestURI {
		case "/set":
			err := manager.Set(r, "key", "Hello, gsession\n")
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
		case "/get":
			val, err := manager.Get(r, "key")
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				break
			}
			w.Write([]byte(val.(string)))
		}
	}

	// Wrap your handler function in gsession middlware
	handler := manager.Use(http.HandlerFunc(sayHello))

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

[ruslan@weasel ~]$ curl -I -c cookie http://localhost:8080/set
HTTP/1.1 200 OK
Set-Cookie: gsession=e7735c38-0368-475a-852f-290774f2679f; Path=/; Expires=Thu, 24 Jan 2019 11:43:52 GMT; HttpOnly
Date: Wed, 23 Jan 2019 11:43:52 GMT

[ruslan@weasel ~]$ curl -b cookie http://localhost:8080/get
Hello, gsession

To use persistent session store with Badger backend

// Give it a directory or leave blank to get default "gsession"
manager := gs.New(gs.NewFileStore("some_directory", 0), 0, 0, 0)

Test

Run go test from the project root

go test -cover

PASS
coverage: 83.7% of statements
ok  	github.com/anhuret/gsession	0.382s

Why?

Why another Go session manager?
This is my humble attempt at learning Go. A session manager seemed like a good choice.
Yes, take it with a grain of salt please.

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSessionNilContext  - request session context is nil
	ErrSessionNilContext = errors.New("request session context is nil")
	// ErrSessionKeyInvalid - session data key does not exist or invalid
	ErrSessionKeyInvalid = errors.New("session data key does not exist or invalid")
	// ErrSessionNoRecord - session record does not exist or invalid
	ErrSessionNoRecord = errors.New("session record does not exist or invalid")
)

Functions

This section is empty.

Types

type Config

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

Config struct

type FileStore

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

FileStore struct

func NewFileStore

func NewFileStore(dir string) *FileStore

NewFileStore creates a new file store Takes directory path for the database files Empty directory string defaults to "session"

func (*FileStore) Create

func (s *FileStore) Create(id string, ses *Session) (err error)

Create adds a new session entry to the store Takes a session ID and Session struct or nil Pass nil to create default session Psss Session pointer to create an entry with pre defined data or overwrite existing

func (*FileStore) Delete

func (s *FileStore) Delete(id string) (err error)

Delete removes Session from the store Takes session ID

func (*FileStore) Expire

func (s *FileStore) Expire(exp time.Duration) (err error)

Expire removes expired records Takes expiration duration

func (*FileStore) Read

func (s *FileStore) Read(id string) (ses *Session, err error)

Read retrieves Session from store Takes session ID If session not found returns ErrSessionNoRecord error

func (*FileStore) Update

func (s *FileStore) Update(id string, run func(*Session)) (err error)

Update runs a function on Session Takes session ID and a function with Session as parameter If session not found returns ErrSessionNoRecord error

type Manager

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

Manager type

func New

func New(store Store, expiry, idle, renew time.Duration) *Manager

New returns new session manager

func (*Manager) Delete

func (m *Manager) Delete(r *http.Request, key string) error

Delete removes session data Takes HTTP request and key

func (*Manager) Get

func (m *Manager) Get(r *http.Request, key string) (interface{}, error)

Get returns session data Takes HTTP request and data key

func (*Manager) Remove

func (m *Manager) Remove(w http.ResponseWriter, r *http.Request) error

Remove deletes existing session record. Generates new session ID Takes HTTP request and response

func (*Manager) Set

func (m *Manager) Set(r *http.Request, key string, val string) error

Set sets new session key/value pair Takes HTTP request, key and value

func (*Manager) Token

func (m *Manager) Token(r *http.Request, token *string) (string, error)

Token sets or gets session token Takes HTTP request and a token string pointer Returns current token or error Pass nil to get the current token Pass string pointer to set a new token

func (*Manager) Use

func (m *Manager) Use(next http.Handler) http.Handler

Use provides middleware session handler

type MemoryStore

type MemoryStore struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

MemoryStore struct

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore creates a new memory store

func (*MemoryStore) Create

func (s *MemoryStore) Create(id string, ses *Session) error

Create adds a new session entry to the store Takes a session ID and Session struct or nil Pass nil to create default session Psss Session pointer to create an entry with pre defined data or overwrite existing

func (*MemoryStore) Delete

func (s *MemoryStore) Delete(id string) error

Delete removes Session from the store Takes session ID

func (*MemoryStore) Expire

func (s *MemoryStore) Expire(exp time.Duration) (err error)

Expire removes expired records Takes expiration duration

func (*MemoryStore) Read

func (s *MemoryStore) Read(id string) (*Session, error)

Read retrieves Session from store Takes session ID If session not found returns ErrSessionNoRecord error

func (*MemoryStore) Update

func (s *MemoryStore) Update(id string, fn func(*Session)) (err error)

Update runs a function on Session Takes session ID and a function with Session as parameter If session not found returns ErrSessionNoRecord error

type Session

type Session struct {
	Origin time.Time
	Tstamp time.Time
	Token  string
	Data   map[string]interface{}
}

Session struct stores session data

type Store

type Store interface {
	Create(string, *Session) error
	Read(string) (*Session, error)
	Update(string, func(*Session)) error
	Delete(string) error
	Expire(time.Duration) error
}

Store interface

Jump to

Keyboard shortcuts

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