Add support for forms, error, etc

This commit is contained in:
ssobolewski 2018-02-10 17:17:14 -07:00
parent 4dc448ad37
commit fabbb6a52c
2 changed files with 55 additions and 6 deletions

View File

@ -7,8 +7,13 @@ type Context struct {
srv *server
w http.ResponseWriter
r *http.Request
vars map[string]string
}
type SnapContent struct {
Username string
AppData interface{}
}
func (c *Context) GetRequest() *http.Request {
return c.r
@ -23,8 +28,43 @@ func (c *Context) GetUser() string {
return c.Username
}
func (c *Context) Error(code int, msg string) {
c.srv.renderError(c.w, code, msg)
}
func (c *Context) Render(tmpl string, content interface{}) {
c.srv.render(c.w, tmpl, content)
}
func (c *Context) RenderEx(tmpl string, content interface{}) {
cnt := SnapContent {
Username:c.Username,
AppData:content,
}
c.srv.render(c.w, tmpl, &cnt)
}
func (c *Context) GetVar(k string) ( string, bool) {
v,ok := c.vars[k]
return v, ok
}
func (c *Context) GetVarDefault(k string,def string) (string) {
v,ok := c.vars[k]
if !ok {
return def
}
return v
}
func (c *Context) ParseForm() error {
return c.r.ParseForm()
}
func (c *Context) FormValue(k string) string {
return c.r.FormValue(k)
}

View File

@ -9,7 +9,7 @@ import (
"strings"
"time"
"path"
"fmt"
"git.thirdmartini.com/pub/fancylog"
"git.thirdmartini.com/pub/snap/auth"
@ -20,7 +20,7 @@ type Server interface {
ServeTLS(keyPath string, certPath string) error
SetDebug(enable bool)
HandleFunc(path string, f func(c *Context)) error
HandleFuncAuthenticated(path string, f func(c *Context)) error
HandleFuncAuthenticated(path string, f func(c *Context)) *mux.Route
}
type server struct {
@ -58,6 +58,7 @@ func (s *server) authenticated(handle func(c *Context)) http.HandlerFunc {
r: r,
w: w,
srv: s,
vars: mux.Vars(r),
}
handle(c)
}
@ -71,6 +72,7 @@ func (s *server) wrapper(handle func(c *Context)) http.HandlerFunc {
r: r,
w: w,
srv: s,
vars: mux.Vars(r),
}
handle(c)
}
@ -114,15 +116,22 @@ func (s *server) render(w http.ResponseWriter, tmpl string, content interface{}
s.getTemplates().ExecuteTemplate(w, tmpl, content)
}
func (s *server) HandleFuncAuthenticated(path string, f func(c *Context)) error {
if s.auth == nil {
return fmt.Errorf("no auth manager provided")
func (s *server) renderError(w http.ResponseWriter, code int, msg string) {
w.WriteHeader(code)
w.Write([]byte(msg))
}
s.router.HandleFunc(path, s.authenticated(f))
func (s *server) HandleFuncAuthenticated(path string, f func(c *Context)) *mux.Route {
if s.auth == nil {
return nil
}
return s.router.HandleFunc(path, s.authenticated(f))
}
func (s *server) HandleFunc(path string, f func(c *Context)) error {
s.router.HandleFunc(path, s.wrapper(f))
return nil