ProfouzorsLinx/pages.go

87 lines
1.8 KiB
Go
Raw Normal View History

2015-09-24 07:44:49 +02:00
package main
import (
2015-10-04 18:47:20 +02:00
"encoding/json"
"fmt"
2015-09-24 07:44:49 +02:00
"net/http"
2015-10-04 18:47:20 +02:00
"strings"
2015-09-24 07:44:49 +02:00
2015-09-24 08:08:44 +02:00
"github.com/flosch/pongo2"
2015-09-24 07:44:49 +02:00
"github.com/zenazn/goji/web"
)
2015-10-04 18:47:20 +02:00
type RespType int
const (
RespPLAIN RespType = iota
RespJSON
RespHTML
RespAUTO
)
func indexHandler(c web.C, w http.ResponseWriter, r *http.Request) {
err := Templates["index.html"].ExecuteWriter(pongo2.Context{
"maxsize": Config.maxSize,
}, w)
2015-09-24 07:44:49 +02:00
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
2015-09-30 06:56:51 +02:00
func pasteHandler(c web.C, w http.ResponseWriter, r *http.Request) {
err := Templates["paste.html"].ExecuteWriter(pongo2.Context{}, w)
if err != nil {
2015-10-04 18:47:20 +02:00
oopsHandler(c, w, r, RespHTML, "")
2015-09-30 06:56:51 +02:00
}
}
func notFoundHandler(c web.C, w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
err := Templates["404.html"].ExecuteWriter(pongo2.Context{}, w)
if err != nil {
2015-10-04 18:47:20 +02:00
oopsHandler(c, w, r, RespHTML, "")
}
}
2015-10-04 18:47:20 +02:00
func oopsHandler(c web.C, w http.ResponseWriter, r *http.Request, rt RespType, msg string) {
if msg == "" {
msg = "Oops! Something went wrong..."
}
if rt == RespHTML {
w.WriteHeader(500)
2015-10-07 09:00:03 +02:00
Templates["oops.html"].ExecuteWriter(pongo2.Context{"msg": msg}, w)
2015-10-04 18:47:20 +02:00
return
} else if rt == RespPLAIN {
w.WriteHeader(500)
2015-10-07 09:00:03 +02:00
fmt.Fprintf(w, "%s", msg)
2015-10-04 18:47:20 +02:00
return
} else if rt == RespJSON {
js, _ := json.Marshal(map[string]string{
"error": msg,
})
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(500)
w.Write(js)
return
} else if rt == RespAUTO {
if strings.EqualFold("application/json", r.Header.Get("Accept")) {
oopsHandler(c, w, r, RespJSON, msg)
} else {
oopsHandler(c, w, r, RespHTML, msg)
}
}
}
2015-09-29 05:46:43 +02:00
func unauthorizedHandler(c web.C, w http.ResponseWriter, r *http.Request) {
w.WriteHeader(401)
err := Templates["401.html"].ExecuteWriter(pongo2.Context{}, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}