1
0
mirror of https://github.com/gofiber/fiber.git synced 2025-02-23 20:44:00 +00:00
2020-11-13 18:30:14 +01:00
..
2020-11-13 18:30:14 +01:00
2020-11-06 19:43:57 +01:00
2020-11-11 19:22:40 +01:00
2020-11-11 23:51:32 +01:00
2020-11-13 18:30:14 +01:00
2020-11-13 18:30:14 +01:00
2020-11-13 18:30:14 +01:00

Session

Session middleware for Fiber that recovers from panics anywhere in the stack chain and handles the control to the centralized ErrorHandler.

Table of Contents

Signatures

func New(config ...Config) fiber.Handler

Examples

Import the middleware package that is part of the Fiber web framework

import (
  "github.com/gofiber/fiber/v2"
  "github.com/gofiber/fiber/v2/middleware/session"
)

After you initiate your Fiber app, you can use the following possibilities:

// Default middleware config
store := session.New()

// This panic will be catch by the middleware
app.Get("/", func(c *fiber.Ctx) error {
	sess, err := store.Get(c)
	if err != nil {
		return c.Status(500).SendString(err.Error())
	}
	defer sess.Save()

	// Get value
	name := sess.Get("name")

	// Set key/value
	sess.Set("name", "john")

	// Delete key
	sess.Delete("name")


	return fmt.Fprintf(ctx, "Welcome %v", name)
})

Config

// Config defines the config for middleware.
type Config struct {
	// Allowed session duration
	// Optional. Default value 24 * time.Hour
	Expiration time.Duration

	// Storage interface to store the session data
	// Optional. Default value memory.New()
	Storage fiber.Storage

	// Name of the session cookie. This cookie will store session key.
	// Optional. Default value "session_id".
	CookieName string

	// Domain of the CSRF cookie.
	// Optional. Default value "".
	CookieDomain string

	// Path of the CSRF cookie.
	// Optional. Default value "".
	CookiePath string

	// Indicates if CSRF cookie is secure.
	// Optional. Default value false.
	CookieSecure bool

	// Indicates if CSRF cookie is HTTP only.
	// Optional. Default value false.
	CookieHTTPOnly bool

	// Indicates if CSRF cookie is HTTP only.
	// Optional. Default value false.
	CookieSameSite string

	// KeyGenerator generates the session key.
	// Optional. Default value utils.UUID
	KeyGenerator func() string
}

Default Config

var ConfigDefault = Config{
	Expiration:   24 * time.Hour,
	CookieName:   "session_id",
	KeyGenerator: utils.UUID,
}