Permalink
Browse files

added cookie sessions

  • Loading branch information...
zeebo committed Sep 5, 2012
1 parent 50d85a7 commit 85b30a6efb917ab8567d3d277d5373b3e12a7f67
Showing with 23 additions and 3 deletions.
  1. +5 −1 context.go
  2. +14 −2 http.go
  3. +4 −0 main.go
@@ -1,12 +1,14 @@
package main
import (
"code.google.com/p/gorilla/sessions"
"labix.org/v2/mgo"
"net/http"
)
type Context struct {
Database *mgo.Database
Session *sessions.Session
}
func (c *Context) Close() {
@@ -19,7 +21,9 @@ func (c *Context) C(name string) *mgo.Collection {
}
func NewContext(req *http.Request) (*Context, error) {
sess, err := store.Get(req, "gostbook")
return &Context{
Database: session.Clone().DB(database),
}, nil
Session: sess,
}, err
}
16 http.go
@@ -1,6 +1,9 @@
package main
import "net/http"
import (
"net/http"
"thegoods.biz/httpbuf"
)
type handler func(http.ResponseWriter, *http.Request, *Context) error
@@ -13,8 +16,17 @@ func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
defer ctx.Close()
//run the handler and grab the error, and report it
err = h(w, req, ctx)
buf := new(httpbuf.Buffer)
err = h(buf, req, ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
//save the session
if err = ctx.Session.Save(req, buf); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
//apply the buffered response to the writer
buf.Apply(w)
}
@@ -2,6 +2,7 @@ package main
import (
"code.google.com/p/gorilla/pat"
"code.google.com/p/gorilla/sessions"
"fmt"
"labix.org/v2/mgo"
"net/http"
@@ -22,6 +23,7 @@ func reverse(name string, things ...interface{}) string {
return u.Path
}
var store sessions.Store
var session *mgo.Session
var database string
var router *pat.Router
@@ -34,6 +36,8 @@ func main() {
}
database = session.DB("").Name
store = sessions.NewCookieStore([]byte(os.Getenv("KEY")))
router = pat.New()
router.Add("GET", "/login", handler(loginForm)).Name("login")
router.Add("GET", "/", handler(hello)).Name("index")

0 comments on commit 85b30a6

Please sign in to comment.