package main import ( "bytes" "fmt" "net/http" "path" "runtime/debug" "strings" ) func (app *application) serverError(w http.ResponseWriter, err error) { trace := fmt.Sprintf("%s\n%s", err.Error(), debug.Stack()) app.errorLog.Print(trace) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) } func (app *application) clientError(w http.ResponseWriter, status int) { http.Error(w, http.StatusText(status), status) } func (app *application) notFound(w http.ResponseWriter) { app.clientError(w, http.StatusNotFound) } func (app *application) cleanUrl(url string) string { s := strings.TrimPrefix(url, "http://") s = strings.TrimPrefix(s, "https://") s = path.Base(path.Clean(s)) s = "http://" + s return s } func (app *application) renderPage(w http.ResponseWriter, status int, page string, data *templateData) { ts, ok := app.templateCache[page] if !ok { err := fmt.Errorf("the template %s does not exist", page) app.serverError(w, err) return } // a buffer to attempt to write the template to // before writing it to the ResponseWriter w buf := new(bytes.Buffer) err := ts.ExecuteTemplate(buf, "base", data) if err != nil { app.serverError(w, err) return } w.WriteHeader(status) buf.WriteTo(w) } func (app *application) renderElem(w http.ResponseWriter, status int, elem string, data *templateData) { ts, ok := app.templateCache[elem] if !ok { err := fmt.Errorf("the template %s does not exist", elem) app.serverError(w, err) return } // a buffer to attempt to write the template to // before writing it to the ResponseWriter w buf := new(bytes.Buffer) err := ts.Execute(buf, data) if err != nil { app.serverError(w, err) return } w.WriteHeader(status) buf.WriteTo(w) }