Sessions
Sessions allow you to store any information specific to a user. Golf has a built-in memory-based session. To enable it, please set app.SessionManager
as the following:
app.SessionManager = Golf.NewMemorySessionManager()
The code below is a simple example of how to use the session to handle user login.
package main
import (
"github.com/dinever/golf"
"strconv"
)
func mainHandler(ctx *golf.Context) {
name, err := ctx.Session.Get("name")
ctx.SetHeader("Content-Type", "text/html;charset=UTF-8")
if err != nil {
ctx.Send("Hello World! Please <a href=\"/login\">log in</a>. Current sessions: " + strconv.Itoa(ctx.App.SessionManager.Count()))
} else {
ctx.Send("Hello " + name.(string) + ". Current sessions: " + strconv.Itoa(ctx.App.SessionManager.Count()))
}
}
func loginHandler(ctx *golf.Context) {
ctx.Loader("default").Render("login.html", make(map[string]interface{}))
}
func loginHandlerPost(ctx *golf.Context) {
ctx.Session.Set("name", ctx.Request.FormValue("name"))
ctx.Send("Hi, " + ctx.Request.FormValue("name"))
}
func main() {
app := golf.New()
app.View.SetTemplateLoader("default", ".")
app.SessionManager = golf.NewMemorySessionManager()
app.Use(golf.SessionMiddleware)
app.Get("/", mainHandler)
app.Post("/login", loginHandlerPost)
app.Get("/login", loginHandler)
app.Run(":9000")
}
<html>
<body>
<form action="/login" method="post">
Name:
<input type="text" name="name">
<input type="submit" value="Sign in">
</form>
</body>
</html>
As memory-based session may not be the best practice, especially for large scaled websites, Golf provides a way to define custom Session
and SessionManager
components, as long as they follow the interface of golf.Session
and golf.SessionManager
:
type SessionManager interface {
sessionID() (string, error)
NewSession() (Session, error)
Session(string) (Session, error)
GarbageCollection()
Count() int
}
type Session interface {
Set(key string, value interface{}) error
Get(key string) (interface{}, error)
Delete(key string) error
SessionID() string
isExpired() bool
}
Updated less than a minute ago