会议的最佳做法(大猩猩/会议) [英] Best practice with sessions (gorilla/sessions)

查看:100
本文介绍了会议的最佳做法(大猩猩/会议)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在开始在golang中使用会话之前,我需要对某些问题的解答



会话示例



  importgithub.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 :))

$ b $ func main(){
store.Options =& session.Options {
域名:localhost,
路径:/ ,
MaxAge:60 * 15,
Secure:false,
HttpOnly:true,
}
}
pre>

Q1:



是否可以在不同名称的同一个域中添加多个会话?

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

你什么时候需要同一个域上的多个会话?



Q2:



从会话中获取变量的最佳做法是什么?
my_session_var = session.Values [foo]



Q3:



如何检查if会话保存是否正确?如果您访问相同的 map 来设置和获取变量?



更新



 包主

导入(
github.com/gorilla/sessions


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


类型处理程序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,出错了!)
}

错误

 #命令行参数
.\mux.go :101:无法将Handler_404(类型func(http.ResponseWriter,* http.Request,* sessions.Session))转换为输入http.HandlerFunc


GO的HTTP处理程序的基本扩展(西蒙怀特黑德)显示了一个例子何处以及何时定义会话。

而不是在 Handler 本身中执行,而且在定义其他处理程序时必须复制大量代码。

使用命名类型,你可以定义你需要的 Handler

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

这将是一个大猩猩会议,而不是一个mgo会话或数据库)



init()函数可以照顾会话的创建(这里是mgo会话,但其他框架会话的想法是一样的)

  func init(){
session,err = mgo.Dial(localhost)

if err!= nil {
log.Println(err)
}
}

你可以确定这个函数类型('处理程序')不会尊重 ServeHTTP()函数,照顾:


  • 会话管理(克隆/关闭)
  • 调用您的实际处理程序(可以有更多参数,而不仅仅是 w r

      func(h handler )ServeHTTP(w http.ResponseWriter,r * http.Request){
    s:= session.Clone()
    推迟s.Close()

    h(w,r,s .DB(example))
    }




然后你可以定义你的实际的 Handler (同样,大于 w - [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是%d岁,user.Name,user.Age)
}
}



您可以在服务器中使用该处理程序:

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

这个想法是限制 main()降到最低,同时拥有包含更多参数的 Handler
允许你可以使用不同的 Handlers 而只需很少的管道工具,只保留 main()来声明不同的路径(和不用于会话和处理程序的初始化)


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

解决方案

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)

这篇关于会议的最佳做法(大猩猩/会议)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆