2015-01-10 22:52:39 -08:00
|
|
|
package authboss
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"path"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Handler augments http.HandlerFunc with a context.
|
2015-02-19 14:34:29 -08:00
|
|
|
type HandlerFunc func(*Context, http.ResponseWriter, *http.Request) error
|
2015-01-10 22:52:39 -08:00
|
|
|
|
|
|
|
// RouteTable is a routing table from a path to a handlerfunc.
|
|
|
|
type RouteTable map[string]HandlerFunc
|
|
|
|
|
|
|
|
// NewRouter returns a router to be mounted at some mountpoint.
|
2015-01-16 22:03:40 -08:00
|
|
|
func NewRouter() http.Handler {
|
2015-01-10 22:52:39 -08:00
|
|
|
mux := http.NewServeMux()
|
|
|
|
|
|
|
|
for name, mod := range modules {
|
|
|
|
for route, handler := range mod.Routes() {
|
2015-02-15 20:07:36 -08:00
|
|
|
fmt.Fprintf(Cfg.LogWriter, "%-10s Register Route: %s\n", "["+name+"]", route)
|
|
|
|
mux.Handle(path.Join(Cfg.MountPath, route), contextRoute{handler})
|
2015-01-10 22:52:39 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return mux
|
|
|
|
}
|
|
|
|
|
|
|
|
type contextRoute struct {
|
2015-01-16 22:03:40 -08:00
|
|
|
fn HandlerFunc
|
2015-01-10 22:52:39 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c contextRoute) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2015-01-15 02:56:13 -08:00
|
|
|
ctx, err := ContextFromRequest(r)
|
|
|
|
if err != nil {
|
2015-02-15 20:07:36 -08:00
|
|
|
fmt.Fprintf(Cfg.LogWriter, "route: Malformed request, could not create context: %v", err)
|
2015-01-15 02:56:13 -08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-02-20 22:02:55 -08:00
|
|
|
ctx.CookieStorer = clientStoreWrapper{Cfg.CookieStoreMaker(w, r)}
|
|
|
|
ctx.SessionStorer = clientStoreWrapper{Cfg.SessionStoreMaker(w, r)}
|
2015-01-10 22:52:39 -08:00
|
|
|
|
2015-02-19 14:34:29 -08:00
|
|
|
err = c.fn(ctx, w, r)
|
|
|
|
if err == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Fprintf(Cfg.LogWriter, "Error Occurred at %s: %v", r.URL.Path, err)
|
|
|
|
switch e := err.(type) {
|
|
|
|
case AttributeErr:
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
case ClientDataErr:
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
2015-02-20 04:03:22 -08:00
|
|
|
case ErrAndRedirect:
|
2015-02-19 14:34:29 -08:00
|
|
|
if len(e.FlashSuccess) > 0 {
|
|
|
|
ctx.CookieStorer.Put(FlashSuccessKey, e.FlashSuccess)
|
|
|
|
}
|
|
|
|
if len(e.FlashError) > 0 {
|
|
|
|
ctx.CookieStorer.Put(FlashErrorKey, e.FlashError)
|
|
|
|
}
|
|
|
|
http.Redirect(w, r, e.Endpoint, http.StatusTemporaryRedirect)
|
|
|
|
case RenderErr:
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
2015-02-20 23:33:35 -08:00
|
|
|
default:
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
2015-02-19 14:34:29 -08:00
|
|
|
}
|
2015-01-10 22:52:39 -08:00
|
|
|
}
|