Skip to content

Instantly share code, notes, and snippets.

@bundah
Created February 4, 2015 21:04
Show Gist options
  • Save bundah/d29cfc5fed6a6cb8428c to your computer and use it in GitHub Desktop.
Save bundah/d29cfc5fed6a6cb8428c to your computer and use it in GitHub Desktop.
Context example that yields panic stacktrace
curl http://127.0.0.1:3000/admin/reports/
package main
import (
"fmt"
"net/http"
"github.com/gocraft/web"
)
type User struct {
Name string
}
type Context struct {
Session map[string]string
}
func (c *Context) LoadSession(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
fmt.Fprintf(rw, "load session")
next(rw, req)
}
type AdminContext struct {
*Context
CurrentAdmin *User
}
func (c *AdminContext) AdminRequired(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
fmt.Fprintf(rw, "admin required")
next(rw, req)
}
func (c *AdminContext) Reports(rw web.ResponseWriter, req *web.Request) {
fmt.Fprintf(rw, "reports \n")
fmt.Fprintf(rw, c.CurrentAdmin.Name)
}
type ApiContext struct {
*Context
AccessToken string
}
func (c *ApiContext) OAuth(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
fmt.Fprintf(rw, "oauth")
next(rw, req)
}
func (c *ApiContext) TicketsIndex(rw web.ResponseWriter, req *web.Request) {
fmt.Fprintf(rw, "tickets index")
}
func main() {
rootRouter := web.New(Context{})
rootRouter.Middleware((*Context).LoadSession)
apiRouter := rootRouter.Subrouter(ApiContext{}, "/api")
apiRouter.Middleware((*ApiContext).OAuth)
apiRouter.Get("/tickets", (*ApiContext).TicketsIndex)
adminRouter := rootRouter.Subrouter(AdminContext{CurrentAdmin: &User{Name: "Bill"}}, "/admin")
adminRouter.Middleware((*AdminContext).AdminRequired)
adminRouter.Get("/reports", (*AdminContext).Reports)
// Given the path namesapce for this router is "/admin", the full path of this route is "/admin/reports"
adminRouter.Get("/reports", (*AdminContext).Reports)
http.ListenAndServe("localhost:3000", rootRouter) // Start the server!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment