按照redisstor docs进行操作,我想修改this代码以使用Redis存储 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()

// 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 := store
    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
 }

但是我得到这个错误:
vendor/app/shared/session/session.go:19:1: syntax error: non-declaration statement outside function body

我想知道这里有什么问题,我该如何解决?

最佳答案

您可以将有问题的代码放入Configure函数中,以替换初始化CookieStore的原始代码。

var (
    // Store is the *redis* store
    Store *redisStore.RediStore
    // Name is the session name
    Name string
)

// ...

// Configure the session cookie store
func Configure(s Session) {
    var err error
    Store, err = redisStore.NewRediStore(10, "tcp", ":6379", "", []byte("secret-key"))
    if err != nil  {
        log.Fatal("error getting redis store : ", err)
    }

    Store.Options = &s.Options
    Name = s.Name
}

关于session - 错误:redisstor函数主体外部的非声明语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57399221/

10-12 06:21