snap/context.go

93 lines
1.4 KiB
Go
Raw Normal View History

2018-02-07 22:25:00 +00:00
package snap
import (
"net/http"
"encoding/json"
"git.thirdmartini.com/pub/snap/auth"
)
2018-02-07 22:25:00 +00:00
type Context struct {
srv *Server
auth *auth.AuthData
2018-02-07 22:25:00 +00:00
w http.ResponseWriter
r *http.Request
2018-02-11 00:17:14 +00:00
vars map[string]string
2018-02-07 22:25:00 +00:00
}
2018-02-11 00:17:14 +00:00
type SnapContent struct {
User string
Theme string
Content interface{}
2018-02-11 00:17:14 +00:00
}
2018-02-07 22:25:00 +00:00
func (c *Context) GetRequest() *http.Request {
return c.r
}
func (c *Context) Writer() http.ResponseWriter {
return c.w
}
func (c *Context) GetUser() string {
if c.auth == nil {
return ""
}
return c.auth.User
2018-02-07 22:25:00 +00:00
}
2018-02-11 00:17:14 +00:00
func (c *Context) Error(code int, msg string) {
c.srv.renderError(c.w, code, msg)
}
func (c *Context) Reply(msg string) {
c.srv.reply(c.w, msg)
}
func (c *Context) ReplyObject(obj interface{}) {
msg, err := json.Marshal(obj)
if err != nil {
c.Error(400, "Internal Server Error")
}
c.Reply(string(msg))
}
2018-02-07 22:25:00 +00:00
func (c *Context) Render(tmpl string, content interface{}) {
c.srv.render(c.w, tmpl, content)
}
2018-02-11 00:17:14 +00:00
func (c *Context) RenderEx(tmpl string, content interface{}) {
cnt := SnapContent {
User: c.GetUser(),
Theme: c.srv.theme,
Content:content,
2018-02-11 00:17:14 +00:00
}
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)
}