Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
added cookie sessions
  • Loading branch information
zeebo committed Sep 5, 2012
1 parent 50d85a7 commit 85b30a6
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
6 changes: 5 additions & 1 deletion context.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() {
Expand All @@ -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 changes: 14 additions & 2 deletions 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

Expand All @@ -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)
}
4 changes: 4 additions & 0 deletions main.go
Expand Up @@ -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"
Expand All @@ -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
Expand All @@ -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")
Expand Down

0 comments on commit 85b30a6

Please sign in to comment.