dongyouji7022 2014-09-29 18:23
浏览 32

会议最佳实践(大猩猩/会议)

Before starting using sessions in golang I need answers to some questions

session example

import "github.com/gorilla/sessions"

var store = sessions.NewCookieStore([]byte("33446a9dcf9ea060a0a6532b166da32f304af0de"))

func Handler(w http.ResponseWriter, r *http.Request){
    session, _ := store.Get(r, "session-name")

    session.Values["foo"] = "bar"
    session.Values[42] = 43
    session.Save(r, w)

    fmt.Fprint(w, "Hello world :)")
}

func main(){
    store.Options = &sessions.Options{
        Domain:     "localhost",
        Path:       "/",
        MaxAge:     60 * 15,
        Secure:     false,
        HttpOnly:   true,
    }
}

Q1:

Is it possible to add multiple sessions on the same domain with different names?

session1, _ := store.Get(r, "session-name-1")
session2, _ := store.Get(r, "session-name-2")

When do you need multiple sessions on the same domain?

Q2:

What is the best practice to get the variables from the session? my_session_var = session.Values["foo"]

Q3:

How to check if the session is saved correctly? If you access the same map to both set and get variables?

update

package main

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

var (
    store = sessions.NewCookieStore([]byte("33446a9dcf9ea060a0a6532b166da32f304af0de"))
)

type handler func(w http.ResponseWriter, r *http.Request, s *sessions.Session)

func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request){
    session, _ := store.Get(r, "session-name")

    h(w, r, session)
}

func Handler_404(w http.ResponseWriter, r *http.Request, s *sessions.Session){
    fmt.Fprint(w, "Oops, something went wrong!")
}

error

# command-line-arguments
.\mux.go:101: cannot convert Handler_404 (type func(http.ResponseWriter, *http.Request, *sessions.Session)) to type http.HandlerFunc
  • 写回答

1条回答 默认 最新

  • dpjjr42626 2014-09-29 18:43
    关注

    The article "BASIC EXTENSION OF GO’S HTTP HANDLERS" (Simon Whitehead) shows an example of where and when to define session.
    Instead of doing it in the Handler itself, and having to duplicate a lot of code when you define other Handlers.

    With a named type, you can define the Handler you need:

    type handler func(w http.ResponseWriter, r *http.Request, db *mgo.Database)
    

    (in your case, it would be a gorilla sessions instead of a mgo session or database)

    The init() function can take care of the session creation (here mgo session, but the idea is the same for other framework sessions)

    func init() {
        session, err = mgo.Dial("localhost")
    
        if err != nil {
            log.Println(err)
        }
    }
    

    And you can make sure this function type ('handler') does respect the ServeHTTP() function, taking care of:

    • the session management (clone/close)
    • calling your actual handler (which can have more parameters than just w and r)

      func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
          s := session.Clone()
          defer s.Close()
      
          h(w, r, s.DB("example"))
      }
      

    Then you can define your actual Handler (again, with more than w and r):

    func myHandler(w http.ResponseWriter, r *http.Request, db *mgo.Database) {
        var users []user
    
        db.C("users").Find(nil).All(&users)
    
        for _, user := range users {
            fmt.Fprintf(w, "%s is %d years old", user.Name, user.Age)
        }
    }
    

    And you can use that handler in your server:

    func main() {
        mux := http.NewServeMux()
        mux.Handle("/", handler(myHandler))
        http.ListenAndServe(":8080", mux)
    }
    

    The idea is to limit the "plumbing" in main() to a minimum, while having an Handler with more parameters (including your session).
    That allows you to use different Handlers with very little plumbing, keeping main() only for the declaration of the different path (and not for the initialization of session and handlers)


    Update 2019: in another related context, see also "How to handle sessions".

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法