session

package module
v0.0.0-...-43541b1 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2024 License: MIT Imports: 7 Imported by: 0

README

GoLang sessions for web apps.

Supported providers:

  • Postgresql (with pgx driver)
  • Redis (with go-redis) See test file for details.

Usage for pg:

import (
	"fmt"
	"context"
	"encoding/gob"				//used for custom data types encoding
	
	"github.com/dronM/session"      	//session manager
	_ "github.com/dronM/session/pg" 	//postgresql session provider
	
	"github.com/jackc/pgx/v4/pgxpool"	//pg driver		
)

// ENC_KEY holds session encrypt key
const ENC_KEY = "4gWv64T54583v8t410-45vkUiopgjw4gwmjRcGkck,ld"

// SomeStruct holds custom data type
type SomeStruct struct {
	IntVal   int
	FloatVal float32
	StrVal   string
}

func main(){
	conn_s := "{USER_NAME}@{HOST}:{PORT}/{DATABASE}"
	//creating session manager with 0 TTL, 0 max idle time,
	//requesting to clear all sessions at 03:00
	SessManager, er := session.NewManager("pg", 0, 0, "03:00", conn_s, ENC_KEY)
	if er != nil {
		panic(fmt.Sprintf("NewManager() fail: %v\n", err))
	}

	// Starting new session with unique random ID
	currentSession, er := SessManager.SessionStart("")
	if er != nil {
		panic(fmt.Sprintf("SessionStart() fail: %v\n", err))
	}

	//Register custom struct for marshaling.
	gob.Register(SomeStruct{})

	// Setting data
	currentSession.Set("strVal", "Some string")
	currentSession.Set("intVal", 125)
	currentSession.Set("floatVal", 3.14)	
	currentSession.Set("customVal", SomeStruct{IntVal: 375, FloatVal: 3.14, StrVal: "Some string value in struct"})
	
	// Flushing to database
	if err := currentSession.Flush(); err != nil {
		panic(fmt.Sprintf("Flush() fail: %v\n", err))
	}

	if err := SessManager.SessionClose(currentSession.SessionID()); err != nil {
		panic(fmt.Sprintf("SessionClose() fail: %v\n", err))
	}	
}

Documentation

Overview

Package session provides support for sessions in web applications. It gives interface for specific session implementation. Session providers are implemented as specific packages. Max session life time, max session idle time, fixed time clearing are supported. See NewManager() function for specific session handling parameters.

Index

Constants

View Source
const (
	TIME_SEC_LAYOUT = "15:04:05"
	TIME_MIN_LAYOUT = "15:04"
)

Variables

This section is empty.

Functions

func Register

func Register(name string, provide Provider)

Register makes a session provider available by the provided name. If Register is called twice with the same name or if driver is nil, it panics.

func WriteToLog

func WriteToLog(w io.Writer, s string, logLevel LogLevel)

Types

type LogLevel

type LogLevel int
const (
	LOG_LEVEL_ERROR LogLevel = iota
	LOG_LEVEL_WARN
	LOG_LEVEL_DEBUG
)

func (LogLevel) String

func (lv LogLevel) String() string

type Manager

type Manager struct {
	SessionsKillTime time.Time //clears all sessions
	// contains filtered or unexported fields
}

Manager structure for holding provider.

func NewManager

func NewManager(providerName string, maxLifeTime int64, maxIdleTime int64, sessionsKillTime string, provParams ...interface{}) (*Manager, error)

NewManager is a Manager create function. providerName is a name of the data storage provider. maxLifeTime is a maximum life of a session in seconds. maxIdleTime is a maximum idle time of a session in seconds. Idling is the time during which a session is not accessed. sessionsKillTime is a time in format 00:00 or 00:00:00 at which all sessions will be killed on dayly bases. See details how session destruction is handled in StartGC() provParams contains provider specific arguments.

func (*Manager) DestroyAllSessions

func (manager *Manager) DestroyAllSessions(l io.Writer, logLev LogLevel)

func (*Manager) GetSessionIDLen

func (manager *Manager) GetSessionIDLen() int

GetSessionIDLen returns session ID length specific for provider.

func (*Manager) InitProvider

func (manager *Manager) InitProvider(provParams []interface{}) error

InitProvider initializes provider with its specific parameters. Should consult specific provider package to know its parameters.

func (*Manager) SessionClose

func (manager *Manager) SessionClose(sid string) error

SessionClose closes session with the given ID.

func (*Manager) SessionDestroy

func (manager *Manager) SessionDestroy(sid string) error

SessionDestroy destroys session by its ID.

func (*Manager) SessionGC

func (manager *Manager) SessionGC(l io.Writer, logLev LogLevel)

func (*Manager) SessionStart

func (manager *Manager) SessionStart(sid string) (Session, error)

SessionStart opens session with the given ID.

func (*Manager) SetMaxIdleTime

func (manager *Manager) SetMaxIdleTime(maxIdleTime int64)

SetMaxIdleTime is an alias for provider SetMaxIdleTime

func (*Manager) SetMaxLifeTime

func (manager *Manager) SetMaxLifeTime(maxLifeTime int64)

SetMaxLifeTime is an alias for provider SetMaxLifeTime

func (*Manager) SetSessionsKillTime

func (manager *Manager) SetSessionsKillTime(sessionsKillTime string) error

SetSessionsKillTime sets time from the given string value

func (*Manager) StartGC

func (manager *Manager) StartGC(l io.Writer, logLev LogLevel)

StartGC starts garbage collection (GC) server for managing sessions destruction. Session can be destroyed:

  • if SessionsKillTime is set, then all sessions will be cleared at that time.
  • if idle time is set, then sessions idling (session access time is controled) more then that time will be cleared.
  • if max life time is set, then sessions will live no more then that specified time, no matter idling or not.

SessionsKillTime runs its own independant gorouting. MaxLifeTime and MaxIdleTime are combined in one gorouting. All thee parameters can be used together. Goroutings are controled by a context an can be cancelled. So it is possible to modify SessionsKillTime/MaxLifeTime/MaxIdleTime and to restart the GC server Server does not generate any output. Instead all errors/comments are sent to io.Writer passed as argument to StartGC() function.

func (*Manager) StopGC

func (manager *Manager) StopGC()

StopGC stops garbage collection server

type Provider

type Provider interface {
	InitProvider(provParams []interface{}) error
	SessionInit(sid string) (Session, error)
	SessionRead(sid string) (Session, error)
	SessionDestroy(sid string) error
	SessionClose(sid string) error
	SessionGC(io.Writer, LogLevel)
	GetSessionIDLen() int
	SetMaxLifeTime(int64)
	GetMaxLifeTime() int64
	SetMaxIdleTime(int64)
	GetMaxIdleTime() int64
	DestroyAllSessions(io.Writer, LogLevel)
}

Provider interface for session provider.

type Session

type Session interface {
	Set(key string, value interface{}) error //set session value
	Put(key string, value interface{}) error //set session value and flushes
	Get(key string, value interface{}) error //get session value
	GetBool(key string) bool                 //get bool session value, false if no key or assertion error
	GetString(key string) string             //get string session value, empty string if no key or assertion error
	GetInt(key string) int64                 //get int64 session value, 0 if no key or assertion error
	GetFloat(key string) float64             //get float64 session value, 0.0 if no key or assertion error
	Delete(key string) error                 //delete session value
	SessionID() string                       //returns current sessionID
	Flush() error                            //flushes data to persistent storage
	TimeCreated() time.Time
	TimeAccessed() time.Time
}

Session interface for session functionality.

Directories

Path Synopsis
Package pg contains postgresql session provider based on jackc connection to PG.
Package pg contains postgresql session provider based on jackc connection to PG.
Package redis contains postgresql session provider based on go-redis client.
Package redis contains postgresql session provider based on go-redis client.

Jump to

Keyboard shortcuts

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