Session


Fiber를 위한 Session 미들웨어입니다.

이 미들웨어는 Storage 패키지를 사용하여 단일 인터페이스를 통해 다양한 데이터베이스를 지원합니다. 이 미들웨어의 기본 구성은 메모리에 데이터를 저장하며, 다른 데이터베이스의 예는 아래를 참조하세요.

Signatures

func New(config ...Config) *Store
func (s *Store) RegisterType(i interface{})
func (s *Store) Get(c *fiber.Ctx) (*Session, error)
func (s *Store) Delete(id string) error
func (s *Store) Reset() error

func (s *Session) Get(key string) interface{}
func (s *Session) Set(key string, val interface{})
func (s *Session) Delete(key string)
func (s *Session) Destroy() error
func (s *Session) Reset() error
func (s *Session) Regenerate() error
func (s *Session) Save() error
func (s *Session) Fresh() bool
func (s *Session) ID() string
func (s *Session) Keys() []string

interface{} 값 저장은 Go 내장 타입으로 제한됩니다.

Examples

Fiber 웹 프레임워크의 미들웨어 패키지를 import 합니다

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

Fiber 앱을 초기화한 후, 다음과 같이 사용할 수 있습니다:

// 기본 설정으로 초기화
// 앱의 모든 세션 저장
store := session.New()

app.Get("/", func(c *fiber.Ctx) error {
    // 스토리지에서 세션 가져오기
    sess, err := store.Get(c)
    if err != nil {
        panic(err)
    }

    // 값 가져오기
    name := sess.Get("name")

    // 키/값 설정
    sess.Set("name", "john")

    // 모든 키 가져오기 
    keys := sess.Keys()

    // 키 삭제
    sess.Delete("name")

    // 세션 삭제
    if err := sess.Destroy(); err != nil {
        panic(err)
    }

  // 이 세션에 대한 특정 만료 시간 설정
  sess.SetExpiry(time.Second * 2)

    // 세션 저장
    if err := sess.Save(); err != nil {
    panic(err)
  }

  return c.SendString(fmt.Sprintf("Welcome %v", name))
})

Config

Property
Type
Description
Default

Expiration

time.Duration

허용된 세션 지속 시간.

24 * time.Hour

Storage

fiber.Storage

세션 데이터를 저장할 Storage 인터페이스.

memory.New()

KeyLookup

string

KeyLookup은 요청에서 세션 ID를 추출하는 데 사용되는 "<source>:<name>" 형식의 문자열입니다.

"cookie:session_id"

CookieDomain

string

쿠키의 도메인.

""

CookiePath

string

쿠키의 경로.

""

CookieSecure

bool

쿠키가 보안되는지 여부.

false

CookieHTTPOnly

bool

쿠키가 HTTP 전용인지 여부.

false

CookieSameSite

string

SameSite 쿠키의 값.

"Lax"

CookieSessionOnly

bool

쿠키가 브라우저 세션 동안만 지속되어야 하는지 결정. true로 설정하면 Expiration은 무시됩니다.

false

KeyGenerator

func() string

KeyGenerator는 세션 키를 생성합니다.

utils.UUIDv4

CookieName (Deprecated)

string

사용 중단: KeyLookup을 사용하세요. 세션 이름.

""

Default Config

var ConfigDefault = Config{
  Expiration:   24 * time.Hour,
  KeyLookup:    "cookie:session_id",
  KeyGenerator: utils.UUIDv4,
  source:       "cookie",
  sessionName:  "session_id",
}

Rewrite

Rewrite middleware rewrites the URL path based on provided rules. It can be helpful for backward compatibility or just creating cleaner and more descriptive links.

Signatures

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

Config

Property
Type
Description
Default

Next

func(*fiber.Ctx) bool

Next defines a function to skip middleware.

nil

Rules

map[string]string

Rules defines the URL path rewrite rules. The values captured in asterisk can be retrieved by index.

(Required)

Examples

package main

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

func main() {
  app := fiber.New()
  
  app.Use(rewrite.New(rewrite.Config{
    Rules: map[string]string{
      "/old":   "/new",
      "/old/*": "/new/$1",
    },
  }))
  
  app.Get("/new", func(c *fiber.Ctx) error {
    return c.SendString("Hello, World!")
  })
  app.Get("/new/*", func(c *fiber.Ctx) error {
    return c.SendString("Wildcard: " + c.Params("*"))
  })
  
  app.Listen(":3000")
}

Test:

curl http://localhost:3000/old
curl http://localhost:3000/old/hello

Constants

const (
  SourceCookie   Source = "cookie"
  SourceHeader   Source = "header"  
  SourceURLQuery Source = "query"
)

Custom Storage/Database

storage 패키지의 모든 storage를 사용할 수 있습니다.

storage := sqlite3.New() // From github.com/gofiber/storage/sqlite3
store := session.New(session.Config{
  Storage: storage,  
})

store를 사용하려면, Examples를 참조하세요.

Last updated