josephspurrier / gowebapp

Basic MVC Web Application in Go
MIT License
1.14k stars 197 forks source link

How to use redis as session backend? #44

Closed k0fi closed 5 years ago

k0fi commented 5 years ago

Hi Joseph, I'd like to use redis as session storage backend in order to bust the performance of my gowebapp but could not figure out how to apply the instructions found at [redistore](https://github.com/boj/redistore) into existing session.go code.

When I modify session.go like this:

package session

package session

import (
    "net/http"

    "github.com/gorilla/sessions"
    redisStore "gopkg.in/boj/redistore.v1"
)

var store *redisStore.RediStore
 var Name string
var err error

store, err = redisStore.NewRediStore(10, "tcp", ":6379", "", []byte("secret-key"))
if err != nil  {
  log.Fatal("error getting redis store : ", err)
}
defer store.Close()

type Session struct {
    Options   sessions.Options `json:"Options"`   
    Name      string           `json:"Name"`      
    SecretKey string           `json:"SecretKey"` 
}

func Configure(s Session) {
    Store := store
    Store.Options = &s.Options
    Name = s.Name
}

 func Instance(r *http.Request) *sessions.Session {
    session, _ := Store.Get(r, Name)
    return session
}

func Empty(sess *sessions.Session) {
    for k := range sess.Values {
        delete(sess.Values, k)
    }
}

But it does not work I get this error

syntax error: non-declaration statement outside function body

Really appreciate if you help me to fix this.

k0fi commented 5 years ago

OK, I figured out how do so:

package session
import (
    "log"
    "net/http"
    "github.com/gorilla/sessions"
    redisStore "gopkg.in/boj/redistore.v1"
)

// Store is the cookie store
var Store *redisStore.RediStore

// Name is the session name
var Name string
var err error

// Session stores session level information
type Session struct {
    Options   sessions.Options `json:"Options"`    
    Name      string           `json:"Name"`       
    SecretKey string           `json:"SecretKey"` 
}

// Configure the session cookie store
func Configure(s Session) {

    Store, err = redisStore.NewRediStore(10, "tcp", ":6379", "", []byte(s.SecretKey))
    if err != nil {
        log.Fatal("error getting redis store : ", err)
    }
    Store.Options = &s.Options
    Name = s.Name
}

// Instance returns a new session, never returns an error
func Instance(r *http.Request) *sessions.Session {
    session, _ := Store.Get(r, Name)
    return session
}

// Empty deletes all the current session values
func Empty(sess *sessions.Session) {
    // Clear out all stored values in the cookie
    for k := range sess.Values {
        delete(sess.Values, k)
    }
}