webweav.ing/cmd/web/helpers.go

80 lines
1.9 KiB
Go
Raw Normal View History

2024-01-22 20:43:46 +00:00
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
}
2024-03-03 17:53:09 +00:00
func (app *application) renderPage(w http.ResponseWriter, status int, page string, data *templateData) {
2024-01-22 20:43:46 +00:00
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)
}
2024-03-03 17:53:09 +00:00
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)
}