Migration This is my new public git source viewer. Source coming soon. Please contact with concerns/bugs. Contact me

internal/core/errorpage.go

4bda28df3ab3dbfcc789dcbbb184cabc8cac9398 · 2.0 KB · 65 lines raw

1 package core
2
3 import (
4 "bytes"
5 "fmt"
6 "html/template"
7 "net/http"
8 )
9
10 // errorTmpl is compiled from a literal, not from the theme's template
11 // files -- a broken view template is exactly the situation this page has
12 // to survive, so it cannot depend on LoadTemplates succeeding.
13 var errorTmpl = template.Must(template.New("error").Parse(`<!doctype html>
14 <html lang="en">
15 <head>
16 <meta charset="utf-8">
17 <meta name="viewport" content="width=device-width, initial-scale=1">
18 <title>{{.Code}} {{.Status}} &middot; {{.Site}}</title>
19 <link rel="stylesheet" href="/static/css/base.css">
20 </head>
21 <body>
22 <main class="wrap error-page">
23 <p class="error-code">{{.Code}}</p>
24 <h1 class="page-title">{{.Status}}</h1>
25 <p class="page-subtitle">{{.Message}}</p>
26 <p><a href="/">&larr; back to {{.Site}}</a></p>
27 </main>
28 </body>
29 </html>
30 `))
31
32 // renderErrorPage never returns an error: if the template somehow fails to
33 // execute, it falls back to a plain-text body rather than propagating.
34 func renderErrorPage(code int, site string) (body []byte, contentType string) {
35 data := struct {
36 Code int
37 Status, Message, Site string
38 }{
39 Code: code,
40 Status: http.StatusText(code),
41 Message: friendlyMessage(code),
42 Site: site,
43 }
44 var buf bytes.Buffer
45 if err := errorTmpl.Execute(&buf, data); err != nil {
46 return []byte(fmt.Sprintf("%d %s\n", code, http.StatusText(code))), "text/plain; charset=utf-8"
47 }
48 return buf.Bytes(), "text/html; charset=utf-8"
49 }
50
51 // friendlyMessage keeps the diagnostic detail out of the response body --
52 // that stays in the server log -- while still telling a human what class
53 // of problem they hit.
54 func friendlyMessage(code int) string {
55 switch code {
56 case http.StatusNotFound:
57 return "We couldn't find that repository, ref, or path."
58 case http.StatusBadRequest:
59 return "That request doesn't look right."
60 case http.StatusRequestEntityTooLarge:
61 return "That response is too large to display in full."
62 default:
63 return "Something went wrong rendering this page. The details were logged."
64 }
65 }