package page import ( "bytes" "errors" "io/fs" "net/http" ) // Render5xx is automatically called if any render fails, // additionally you can call it for your own uses. It will // try to use the 5xx template but will fall back to a plain // page if that fails. func Render5xx(w http.ResponseWriter, r *http.Request, vars map[string]interface{}, statusCode int) { p := NewPage(TemplateDirectory + "/5xx") buf := &bytes.Buffer{} err := p.Render(buf) if err != nil { logErr(r, "while trying 5xx", err) http.Error(w, "Internal server error", statusCode) return } w.WriteHeader(statusCode) _, _ = w.Write(buf.Bytes()) logReq(r, statusCode) } // Render4xx is mostly used to render a 404 page, pulls from 404 template. // automatically called by Render if a page is missing. func Render4xx(w http.ResponseWriter, r *http.Request, vars map[string]interface{}, statusCode int) { p := NewPage(TemplateDirectory + "/4xx") buf := &bytes.Buffer{} err := p.Render(buf) if err != nil { logErr(r, "while trying 404", err) Render5xx(w, r, vars, http.StatusInternalServerError) return } w.WriteHeader(statusCode) _, err = w.Write(buf.Bytes()) if err != nil { Render5xx(w, r, nil, http.StatusInternalServerError) return } logReq(r, statusCode) } // Render is a lower level option, allowing you to specify local // variables and the status code in which to return. func Render(w http.ResponseWriter, r *http.Request, path string, vars map[string]interface{}, statusCode int) { // Sepcifically use the specified path for the page p := NewPage(path) if vars != nil { p.Vars = vars } buf := &bytes.Buffer{} err := p.Render(buf) if err != nil { if errors.Is(err, fs.ErrNotExist) { Render4xx(w, r, vars, http.StatusNotFound) return } logErr(r, "rendering encountered", err) Render5xx(w, r, vars, http.StatusInternalServerError) return } w.WriteHeader(statusCode) _, err = w.Write(buf.Bytes()) if err != nil { logErr(r, "while writing to buf", err) Render5xx(w, r, nil, http.StatusInternalServerError) return } logReq(r, statusCode) } // RenderWithVars allows you to specify a specific page and whether or not // you wish to override vars. If left nil they will not be overridden. // Also see RenderForPath if you don't need to override them. func RenderWithVars(w http.ResponseWriter, r *http.Request, path string, vars map[string]interface{}) { Render(w, r, path, vars, http.StatusOK) } // RenderForPath takes the path to a page and finish up the rendering // Allowing you to place logic on what page is rendered by your handlers. func RenderForPath(w http.ResponseWriter, r *http.Request, path string) { RenderWithVars(w, r, path, nil) }