dongya6381
2019-01-03 19:01
浏览 199
已采纳

如何在Golang中以不同的软件包使用Gorilla Sessions

I have main package (main.go):

package main

import (
  "github.com/gorilla/sessions"
  ...
)

func main() {
  var store = sessions.NewCookieStore([]byte("secret"))

  http.HandleFunc("/", routes.Index)

  http.ListenAndServe(":8080", nil)
  ...

And I have another package (index.go):

package routes

import (
  "github.com/gorilla/sessions"
  ..
)

func Index(res http.ResponseWriter, req *http.Request) {
  session, _ := store.Get(req, "session-name")
  ...

How can I get session value from another package? Or should I pass it to my Handler (if yes how to do it?).

I am new in Golang. Please, help.

图片转代码服务由CSDN问答提供 功能建议

我有主软件包(main.go):

  包main 
 
import(
“ github.com/gorilla/sessions"
 ... 
)
 
func main(){
 var store = session.NewCookieStore([] byte(” secret“  ))
 
 http.HandleFunc(“ /”,route.Index)
 
 http.ListenAndServe(“:8080”,nil)
 ... 
   
  
 

我还有另一个包(index.go):

 包路由
 
导入(
“ github.com/gorilla/sessions"
  .. 
)
 
func索引(res http.ResponseWriter,req * http.Request){
会话,_:= store.Get(req,“会话名称”)
 ... 
 <  / code>  
 
 

如何从另一个包中获取会话值? 还是应该将其传递给我的处理程序(如果是,该怎么做?)。

我是Golang的新手。 请帮助。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanjia2415 2019-01-03 20:38
    已采纳

    I generally wrap my dependencies in their own package, which let's me abstract away some of the common things I do. For sessions, I usually use the same session name most of the time, so I would usually have something like this:

    package sessions
    
    import (
        "os"
        gsessions "github.com/gorilla/sessions"
    )
    
    var store = gsessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))
    
    func Get(req *http.Request) (*gsessions.Session, error) {
        return store.Get(req, "default-session-name")
    }
    
    func GetNamed(req *http.Request, name string) (*gsessions.Session, error) {
        return store.Get(req, name)
    }
    

    And then anywhere else you can just import your own sessions package:

    import (
        "net/http"
        "github.com/yourpackage/sessions"
    )
    
    func Index(rw http.ResponseWriter, r *http.Request) {
        session, err := sessions.Get(r)
        if err != nil {
            panic(err)
        }
        session.Values["test"] = "test"
        session.Save(r, rw)
    }
    

    Even better would be to only return an interface of some sort from sessions, and completely wrap the gorilla/sessions so that aren't dependent on it anywhere except for your own sessions package.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题