Browse Source

clean-up middleware

cleanup
Lars Hoogestraat 8 months ago
parent
commit
aca7f56fa2
  1. 30
      middleware/json_handler.go
  2. 6
      middleware/middleware_util.go
  3. 7
      middleware/template.go
  4. 18
      middleware/template_handler.go
  5. 16
      middleware/xml_handler.go

30
middleware/json_handler.go

@ -23,7 +23,7 @@ type JSONHandler struct {
type JHandler func(*AppContext, http.ResponseWriter, *http.Request) (*models.JSONData, error)
func (fn JSONHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
statusCode := 200
code := http.StatusOK
rw.Header().Set("Content-Type", "application/json")
@ -32,34 +32,34 @@ func (fn JSONHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
if err != nil {
switch e := err.(type) {
case *httperror.Error:
statusCode = e.HTTPStatus
code = e.HTTPStatus
default:
statusCode = 500
code = http.StatusInternalServerError
logger.Log.Error(e)
}
logger.Log.Error(err)
mjson, err2 := json.Marshal(err)
if err2 != nil {
logger.Log.Error(err2)
http.Error(rw, err2.Error(), http.StatusInternalServerError)
j, err := json.Marshal(err)
if err != nil {
logger.Log.Error(err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
rw.WriteHeader(statusCode)
rw.Write(mjson)
rw.WriteHeader(code)
rw.Write(j)
return
}
mjson, err2 := json.Marshal(data)
j, err := json.Marshal(data)
if err2 != nil {
http.Error(rw, err2.Error(), http.StatusInternalServerError)
rw.WriteHeader(500)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.WriteHeader(statusCode)
rw.Write(mjson)
rw.WriteHeader(code)
rw.Write(j)
}

6
middleware/middleware_util.go

@ -80,6 +80,7 @@ func setCookie(rw http.ResponseWriter, name, path, data string) {
func getFlash(w http.ResponseWriter, r *http.Request, name string) (string, error) {
c, err := r.Cookie(name)
if err != nil {
switch err {
case http.ErrNoCookie:
@ -88,7 +89,9 @@ func getFlash(w http.ResponseWriter, r *http.Request, name string) (string, erro
return "", err
}
}
value, err := base64.StdEncoding.DecodeString(c.Value)
if err != nil {
return "", err
}
@ -98,7 +101,8 @@ func getFlash(w http.ResponseWriter, r *http.Request, name string) (string, erro
Name: name,
MaxAge: -1,
Expires: time.Unix(1, 0),
Path: "/"}
Path: "/",
}
http.SetCookie(w, dc)

7
middleware/template.go

@ -49,6 +49,7 @@ func NotFound(ctx *AppContext, rw http.ResponseWriter, r *http.Request) *Templat
getFlash(rw, r, "SuccessMsg")
session, _ := ctx.SessionService.Get(rw, r)
if session != nil && strings.HasPrefix(r.URL.EscapedPath(), "/admin") {
return &Template{
Name: "admin/error",
@ -156,8 +157,7 @@ func FuncMap(ss models.SiteService, settings *settings.Settings) template.FuncMa
return t.Time.In(time.Local).Format("January 2, 2006 at 3:04 PM")
},
"HumanizeFilesize": func(size int64) string {
fs := cfg.FileSize(size)
return fs.HumanReadable()
return cfg.FileSize(size).HumanReadable()
},
"FormatDateTime": func(t time.Time) string {
return t.In(time.Local).Format("January 2, 2006 at 3:04 PM")
@ -184,8 +184,7 @@ func FuncMap(ss models.SiteService, settings *settings.Settings) template.FuncMa
return template.HTML(models.MarkdownToHTML([]byte(s)))
},
"NToBr": func(in string) template.HTML {
out := models.NewlineToBr(models.EscapeHTML(in))
return template.HTML(out)
return template.HTML(models.NewlineToBr(models.EscapeHTML(in)))
},
"EscapeHTML": func(in string) string {
return html.EscapeString(in)

18
middleware/template_handler.go

@ -34,7 +34,8 @@ type Handler func(*AppContext, http.ResponseWriter, *http.Request) *Template
func (fn TemplateHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
var errorMsg, warnMsg, successMsg string
statusCode := 200
code := http.StatusOK
ip := getIP(r)
en := logger.Log.WithField("ip", ip)
@ -60,7 +61,7 @@ func (fn TemplateHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
switch e := t.Err.(type) {
case *httperror.Error:
statusCode = e.HTTPStatus
code = e.HTTPStatus
en.Error(e)
errorMsg = e.DisplayMsg
default:
@ -99,14 +100,14 @@ func (fn TemplateHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
t.Data[csrf.TemplateTag] = csrf.TemplateField(r)
t.Data["active"] = t.Active
rw.WriteHeader(statusCode)
rw.WriteHeader(code)
if err := fn.AppCtx.Templates.ExecuteTemplate(rw, t.Name, t.Data); err != nil {
en.Error(err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
} else {
statusCode = http.StatusFound
code = http.StatusFound
if len(errorMsg) > 0 {
setCookie(rw, "ErrorMsg", "/", errorMsg)
} else if len(warnMsg) > 0 {
@ -114,7 +115,7 @@ func (fn TemplateHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
} else if len(successMsg) > 0 {
setCookie(rw, "SuccessMsg", "/", successMsg)
}
http.Redirect(rw, r, path.Clean(t.RedirectURL()), statusCode)
http.Redirect(rw, r, path.Clean(t.RedirectURL()), code)
}
}
@ -135,6 +136,7 @@ func (ctx AppContext) AuthHandler(handler http.Handler) http.Handler {
}
userid, ok := session.GetValue("userid").(int)
if !ok {
logger.Log.Errorf("userid is not an integer %v", userid)
@ -148,6 +150,7 @@ func (ctx AppContext) AuthHandler(handler http.Handler) http.Handler {
}
u, err := ctx.UserService.GetByID(userid)
if err != nil {
logger.Log.Error(err)
rw.WriteHeader(http.StatusUnauthorized)
@ -159,8 +162,7 @@ func (ctx AppContext) AuthHandler(handler http.Handler) http.Handler {
return
}
ctx := context.WithValue(r.Context(), UserContextKey, u)
handler.ServeHTTP(rw, r.WithContext(ctx))
handler.ServeHTTP(rw, r.WithContext(context.WithValue(r.Context(), UserContextKey, u)))
}
return http.HandlerFunc(fn)
}
@ -195,7 +197,7 @@ func (ctx AppContext) RequireAdmin(handler http.Handler) http.Handler {
func User(r *http.Request) (*models.User, error) {
v := r.Context().Value(UserContextKey)
if v == nil {
return nil, httperror.InternalServerError(errors.New("user is not available in context. is the authentication handler in chain?"))
return nil, httperror.InternalServerError(errors.New("user is not available in context"))
}
return v.(*models.User), nil

16
middleware/xml_handler.go

@ -26,22 +26,22 @@ func (fn XMLHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
if err != nil {
logger.Log.Error(err)
x, err2 := xml.Marshal(err)
xml, err := xml.Marshal(err)
if err2 != nil {
logger.Log.Error(err2)
http.Error(rw, err2.Error(), http.StatusInternalServerError)
if err != nil {
logger.Log.Error(err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
rw.Write(x)
rw.Write(xml)
return
}
x, err2 := xml.MarshalIndent(h.Data, "", "\t")
x, err := xml.MarshalIndent(h.Data, "", "\t")
if err2 != nil {
http.Error(rw, err2.Error(), http.StatusInternalServerError)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}

Loading…
Cancel
Save