Skip to content

utahta/echo-sessions

Repository files navigation

Sessions middleware for Echo

GitHub release Build Status

This is a package of sessions middleware for Echo.
A thin gorilla/sessions wrapper.

Install

$ go get -u github.com/utahta/echo-sessions

Middleware usage

import (
    "github.com/boj/redistore"
    "github.com/utahta/echo-sessions"
    "github.com/labstack/echo"
)

store, _ := redistore.NewRediStore(10, "tcp", ":6379", "", []byte("secret-key"))

e := echo.New()
e.Use(sessions.Sessions("SESSID", store))

Helpers usage

import "github.com/utahta/echo-sessions"

func example(c echo.Context) {
    sessions.Set(c, "key", "value")
    
    dst := sessions.GetRaw(c, "key")
    
    var dst string
    ok, err := sessions.Get(c, "key", &dst)
    
    var dst string
    ok := sessions.MustGet(c, "key", &dst)
    
    sessions.Delete(c, "key")
    
    ok := sessions.Exists(c, "key")
    
    sessions.Clear(c)
    
    sessions.Flashes(c vars...)
    
    sessions.AddFlash(c, value, vars...)
    
    err := sessions.Save(c)
}

Learn more

Get the session handler

s := sessions.MustStart()

Set key and value

s.Set("key", "value")

Get value by key

var v string
ok, err := s.Get("key", &v)

or

var v string
ok := s.MustGet("key", &v)

Get raw value by key

v := s.GetRaw("key") // returns (interface{})

Check key exists

if !s.Exists("key") {
    s.Set("key", "new value")
}

or

var v string
if ok, err := s.Get("example1", &v); !ok && err == nil {
    s.Set("example1", "new value")
}

if ok := s.MustGet("example2", &v); !ok {
    s.Set("example2", "new value")
}

Delete key

s.Delete("key")

Save this session

err := s.Save()

Contributing

  1. Fork it ( https://github.com/utahta/echo-sessions/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request