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

如何在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.

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?