refactor: Make view logic private

This commit is contained in:
Daan Sprenkels 2019-09-19 21:42:01 +02:00
parent a4ad82d6dd
commit 173ae7665b
2 changed files with 36 additions and 36 deletions

View File

@ -74,28 +74,28 @@ func (t PasteState) String() string {
} }
func indexGetHandler(w http.ResponseWriter, r *http.Request) { func indexGetHandler(w http.ResponseWriter, r *http.Request) {
Render(w, r, "index", nil) render(w, r, "index", nil)
} }
func indexPostHandler(w http.ResponseWriter, r *http.Request) { func indexPostHandler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(50 * 1000 * 1000); err != nil { if err := r.ParseMultipartForm(50 * 1000 * 1000); err != nil {
log.Printf("error: %v\n", err) log.Printf("error: %v\n", err)
RenderInternalServerError(w, r, err) renderInternalServerError(w, r, err)
return return
} }
// Determine what kind of post this is, currently only `shorten=...` // Determine what kind of post this is, currently only `shorten=...`
if len(r.PostForm) == 0 { if len(r.PostForm) == 0 {
RenderError(w, r, http.StatusBadRequest, "empty body in POST request\n") renderError(w, r, http.StatusBadRequest, "empty body in POST request\n")
return return
} }
shorten_values, prs := r.PostForm["shorten"] shorten_values, prs := r.PostForm["shorten"]
if !prs { if !prs {
RenderError(w, r, http.StatusBadRequest, "no 'shorten' param given\n") renderError(w, r, http.StatusBadRequest, "no 'shorten' param given\n")
return return
} }
if len(shorten_values) != 1 { if len(shorten_values) != 1 {
RenderError(w, r, http.StatusBadRequest, "only one 'shorten' param is allowed per request\n") renderError(w, r, http.StatusBadRequest, "only one 'shorten' param is allowed per request\n")
return return
} }
@ -124,11 +124,11 @@ func pasteGetHandlerInner(w http.ResponseWriter, r *http.Request, noRedirect, sh
return err return err
}); err != nil { }); err != nil {
log.Printf("error: %v\n", err) log.Printf("error: %v\n", err)
RenderInternalServerError(w, r, err) renderInternalServerError(w, r, err)
return return
} }
if storedPaste == nil { if storedPaste == nil {
RenderError(w, r, http.StatusNotFound, "url key not found in the database") renderError(w, r, http.StatusNotFound, "url key not found in the database")
return return
} }
@ -143,7 +143,7 @@ func pasteGetHandlerInner(w http.ResponseWriter, r *http.Request, noRedirect, sh
"Paste": storedPaste, "Paste": storedPaste,
"IsOwner": isOwner, "IsOwner": isOwner,
} }
Render(w, r, "pasteMeta", data) render(w, r, "pasteMeta", data)
return return
} }
@ -154,18 +154,18 @@ func pasteGetHandlerInner(w http.ResponseWriter, r *http.Request, noRedirect, sh
urlParse, err := url.Parse(rawurl) urlParse, err := url.Parse(rawurl)
if err != nil { if err != nil {
log.Printf("error: invalid URL ('%v') in database for key '%v': %v\n", rawurl, storedPaste.Key, err) log.Printf("error: invalid URL ('%v') in database for key '%v': %v\n", rawurl, storedPaste.Key, err)
RenderInternalServerError(w, r, "invalid url in database") renderInternalServerError(w, r, "invalid url in database")
return return
} }
http.Redirect(w, r, urlParse.String(), http.StatusSeeOther) http.Redirect(w, r, urlParse.String(), http.StatusSeeOther)
} }
w.Write(storedPaste.Content) w.Write(storedPaste.Content)
case StateDeleted: case StateDeleted:
RenderError(w, r, http.StatusGone, "key has been deleted") renderError(w, r, http.StatusGone, "key has been deleted")
default: default:
log.Printf("error: invalid storedPaste.State (%v) for key '%v'\n", storedPaste.State, storedPaste.Key) log.Printf("error: invalid storedPaste.State (%v) for key '%v'\n", storedPaste.State, storedPaste.Key)
msg := fmt.Sprintf("internal server error: invalid storedPaste.State (%v\n)", storedPaste.State) msg := fmt.Sprintf("internal server error: invalid storedPaste.State (%v\n)", storedPaste.State)
RenderInternalServerError(w, r, msg) renderInternalServerError(w, r, msg)
} }
} }
@ -174,15 +174,15 @@ func shortenPostHandler(w http.ResponseWriter, r *http.Request) {
userURL, err := url.ParseRequestURI(rawurl) userURL, err := url.ParseRequestURI(rawurl)
if err != nil { if err != nil {
msg := fmt.Sprintf("invalid url (%v): %v", err, rawurl) msg := fmt.Sprintf("invalid url (%v): %v", err, rawurl)
RenderError(w, r, http.StatusBadRequest, msg) renderError(w, r, http.StatusBadRequest, msg)
return return
} }
if userURL.Scheme == "" { if userURL.Scheme == "" {
RenderError(w, r, http.StatusBadRequest, "invalid url (unspecified scheme)") renderError(w, r, http.StatusBadRequest, "invalid url (unspecified scheme)")
return return
} }
if userURL.Host == "" { if userURL.Host == "" {
RenderError(w, r, http.StatusBadRequest, "invalid url (unspecified host)") renderError(w, r, http.StatusBadRequest, "invalid url (unspecified host)")
return return
} }
@ -202,7 +202,7 @@ func shortenPostHandler(w http.ResponseWriter, r *http.Request) {
return err return err
}); err != nil { }); err != nil {
log.Printf("error: %v\n", err) log.Printf("error: %v\n", err)
RenderInternalServerError(w, r, err) renderInternalServerError(w, r, err)
return return
} }
@ -210,7 +210,7 @@ func shortenPostHandler(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
err = errors.Wrap(err, "parsing url") err = errors.Wrap(err, "parsing url")
log.Printf("error: %v\n", err) log.Printf("error: %v\n", err)
RenderInternalServerError(w, r, err) renderInternalServerError(w, r, err)
return return
} }
var base64OwnerToken = make([]byte, 24) var base64OwnerToken = make([]byte, 24)

View File

@ -23,12 +23,12 @@ import (
) )
// Plain text templates // Plain text templates
var TextBaseTemplate *text.Template = text.Must(text.New("").Parse(string(MustAsset("templates/txt/base.txt.tmpl")))) var textBaseTemplate *text.Template = text.Must(text.New("").Parse(string(MustAsset("templates/txt/base.txt.tmpl"))))
var HTMLBaseTemplate *html.Template = html.Must(html.New("").Parse(string(MustAsset("templates/html/base.html.tmpl")))) var htmlBaseTemplate *html.Template = html.Must(html.New("").Parse(string(MustAsset("templates/html/base.html.tmpl"))))
// Template collections // Template collections
var TextTemplates = make(map[string]*text.Template, 0) var textTemplates = make(map[string]*text.Template, 0)
var HTMLTemplates = make(map[string]*html.Template, 0) var htmlTemplates = make(map[string]*html.Template, 0)
// Used by resolveResponseContentType // Used by resolveResponseContentType
var acceptHeaderMediaRangeRegex = regexp.MustCompile(`^\s*([^()<>@,;:\\"/\[\]?.=]+)/([^()<>@,;:\\"/\[\]?.=]+)\s*$`) var acceptHeaderMediaRangeRegex = regexp.MustCompile(`^\s*([^()<>@,;:\\"/\[\]?.=]+)/([^()<>@,;:\\"/\[\]?.=]+)\s*$`)
@ -39,23 +39,23 @@ var acceptHeaderWeight = regexp.MustCompile(`^\s*q=0(?:\.([0-9]{0,3}))|1(?:\.0{0
func init() { func init() {
for _, tmplPath := range AssetNames() { for _, tmplPath := range AssetNames() {
if mustMatch("templates/txt/*.txt.tmpl", tmplPath) { if mustMatch("templates/txt/*.txt.tmpl", tmplPath) {
base := text.Must(TextBaseTemplate.Clone()) base := text.Must(textBaseTemplate.Clone())
tmpl := text.Must(base.Parse(string(MustAsset(tmplPath)))) tmpl := text.Must(base.Parse(string(MustAsset(tmplPath))))
tmplName := strings.TrimSuffix(filepath.Base(tmplPath), ".txt.tmpl") tmplName := strings.TrimSuffix(filepath.Base(tmplPath), ".txt.tmpl")
TextTemplates[tmplName] = tmpl textTemplates[tmplName] = tmpl
continue continue
} }
if mustMatch("templates/html/*.html.tmpl", tmplPath) { if mustMatch("templates/html/*.html.tmpl", tmplPath) {
base := html.Must(HTMLBaseTemplate.Clone()) base := html.Must(htmlBaseTemplate.Clone())
tmpl := html.Must(base.Parse(string(MustAsset(tmplPath)))) tmpl := html.Must(base.Parse(string(MustAsset(tmplPath))))
tmplName := strings.TrimSuffix(filepath.Base(tmplPath), ".html.tmpl") tmplName := strings.TrimSuffix(filepath.Base(tmplPath), ".html.tmpl")
HTMLTemplates[tmplName] = tmpl htmlTemplates[tmplName] = tmpl
continue continue
} }
} }
// Sanity check. Both maps should not be empty // Sanity check. Both maps should not be empty
if len(TextTemplates) == 0 || len(HTMLTemplates) == 0 { if len(textTemplates) == 0 || len(htmlTemplates) == 0 {
panic("template loading failed") panic("template loading failed")
} }
} }
@ -72,7 +72,7 @@ func parseFail(tmplName string, err error) {
panic(errors.Wrapf(err, "parsing of %v failed", tmplName)) panic(errors.Wrapf(err, "parsing of %v failed", tmplName))
} }
func Render(w http.ResponseWriter, r *http.Request, tmplName string, data map[string]interface{}) { func render(w http.ResponseWriter, r *http.Request, tmplName string, data map[string]interface{}) {
contentType, err := resolveResponseContentType(r, []string{"text/plain", "text/html"}) contentType, err := resolveResponseContentType(r, []string{"text/plain", "text/html"})
if err != nil { if err != nil {
w.WriteHeader(http.StatusNotAcceptable) w.WriteHeader(http.StatusNotAcceptable)
@ -82,25 +82,25 @@ func Render(w http.ResponseWriter, r *http.Request, tmplName string, data map[st
switch contentType { switch contentType {
case "text/plain": case "text/plain":
w.Header().Set("Content-Type", "text/plain") w.Header().Set("Content-Type", "text/plain")
tmpl := TextTemplates[tmplName] tmpl := textTemplates[tmplName]
if tmpl == nil { if tmpl == nil {
err = fmt.Errorf("'%v' not in TextTemplates", tmplName) err = fmt.Errorf("'%v' not in textTemplates", tmplName)
break break
} }
err = tmpl.Execute(w, data) err = tmpl.Execute(w, data)
case "text/html": case "text/html":
w.Header().Set("Content-Type", "text/html") w.Header().Set("Content-Type", "text/html")
tmpl := HTMLTemplates[tmplName] tmpl := htmlTemplates[tmplName]
if tmpl == nil { if tmpl == nil {
err = fmt.Errorf("'%v' not in HTMLTemplates", tmplName) err = fmt.Errorf("'%v' not in htmlTemplates", tmplName)
break break
} }
// Construct a (lazy) plain-text view for inclusion in <pre> // Construct a (lazy) plain-text view for inclusion in <pre>
pre := func() string { pre := func() string {
tmpl := TextTemplates[tmplName] tmpl := textTemplates[tmplName]
if tmpl == nil { if tmpl == nil {
panic(fmt.Errorf("'%v' not in TextTemplates", tmplName)) panic(fmt.Errorf("'%v' not in textTemplates", tmplName))
} }
var buf bytes.Buffer var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil { if err := tmpl.Execute(&buf, data); err != nil {
@ -121,14 +121,14 @@ func Render(w http.ResponseWriter, r *http.Request, tmplName string, data map[st
} }
} }
func RenderError(w http.ResponseWriter, r *http.Request, status int, msg string) { func renderError(w http.ResponseWriter, r *http.Request, status int, msg string) {
w.WriteHeader(status) w.WriteHeader(status)
Render(w, r, "error", map[string]interface{}{"Message": msg}) render(w, r, "error", map[string]interface{}{"Message": msg})
} }
func RenderInternalServerError(w http.ResponseWriter, r *http.Request, err interface{}) { func renderInternalServerError(w http.ResponseWriter, r *http.Request, err interface{}) {
msg := fmt.Sprintf("internal server error: %v", err) msg := fmt.Sprintf("internal server error: %v", err)
RenderError(w, r, http.StatusInternalServerError, msg) renderError(w, r, http.StatusInternalServerError, msg)
} }
// Merge the second data map into the first one, overwriting any key that is // Merge the second data map into the first one, overwriting any key that is