-
Notifications
You must be signed in to change notification settings - Fork 2
session
Session is used to preserve some state between the client and the server. Surfer doesn't provide a standard method for sessions, this is my design. Every application is different, and has different needs when it comes to session persistance. The needs for such persistence varies a lot, some applications don't need any sort of session persistance at all, others depend entirely on. Despite these differences we provide a design pattern for session handling.
To handle sessions you need two separate pieces of data that is transfered over two different channels. Firstly, a token given to the client that identifies them as the owner of the session. This may be a cookie or query-data or in some cases even a custom HTTP header. Secondly, some kind of persistant storage is needed, where the actual data is to be stored. This is maybe something like Redis, memchaced or a relational database. Once again this varies from application to application.
type SessionH struct {
surfer.Handler
db DBconnection
session map[string][string]
}
This is an example of adding sessions to a handler. Where DBConnection is your database connection, it doesn't matter if it is Redis, MongoDB, PostgreSQL. Furthermore, the session can be any object, nothing forces you to use a string map.
func (this *SHandler) Prepare() {
if sid, err := this.GetSecureCookie("sid"); err != nil {
this.session = this.db.get("session", sid)
}
return true
}
The session is retrived in the prepare step. We first get the session id from a secure cookie and then retrive the session object from the db.
type IndexH struct {
SHandler
}
func (this *IndexH) Index() {
if _, e := this.session["user"] { // or len(this.session)
this.RedirectUrl("/login")
return
}
this.Data["flash"] = "Hello " + this.session["user"]
}
The above code shows how the retrived session object can be used to construct the page.
import "surfer"
type SessionH struct {
surfer.Handler
db DBconnection
session map[string][string]
}
func (this *SHandler) Prepare() {
if sid, err := this.GetSecureCookie("sid"); err != nil {
this.session = this.db.get("session", sid)
}
}
type IndexH struct {
SHandler
}
func (this *IndexH) Index() {
if _, e := this.session["user"] { // or len(this.session)
this.RedirectUrl("/login")
return
}
this.Data["flash"] = "Hello " + this.session["user"]
}
```