helpers.go
| 1 | package handler |
| 2 | |
| 3 | import ( |
| 4 | "log" |
| 5 | "net/http" |
| 6 | "strconv" |
| 7 | |
| 8 | "github.com/go-chi/chi/v5" |
| 9 | ) |
| 10 | |
| 11 | // parseID reads the {id} route parameter. It writes a 400 and reports false when |
| 12 | // the value isn't a valid id, so callers can simply return. |
| 13 | func parseID(w http.ResponseWriter, r *http.Request) (int64, bool) { |
| 14 | id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) |
| 15 | if err != nil { |
| 16 | http.Error(w, "Invalid ID", http.StatusBadRequest) |
| 17 | return 0, false |
| 18 | } |
| 19 | return id, true |
| 20 | } |
| 21 | |
| 22 | // sortFromRequest returns the sort order for a listing page. An explicit ?sort= |
| 23 | // is remembered in a cookie; without one the last choice is restored, so the |
| 24 | // order survives the auto-refresh that reloads these pages. |
| 25 | func sortFromRequest(w http.ResponseWriter, r *http.Request, cookie, defaultSort string) string { |
| 26 | sortBy := r.URL.Query().Get("sort") |
| 27 | if sortBy == "" { |
| 28 | return getCookie(r, cookie, defaultSort) |
| 29 | } |
| 30 | setCookie(w, cookie, sortBy) |
| 31 | return sortBy |
| 32 | } |
| 33 | |
| 34 | // serverError logs the underlying failure and shows the user a generic message. |
| 35 | // Internal error strings can carry filesystem paths and SQL text, so they are |
| 36 | // kept out of the response. |
| 37 | func (h *Handler) serverError(w http.ResponseWriter, r *http.Request, context string, err error) { |
| 38 | log.Printf("%s %s: %s: %v", r.Method, r.URL.Path, context, err) |
| 39 | http.Error(w, "Something went wrong. Please try again.", http.StatusInternalServerError) |
| 40 | } |
| 41 | |
| 42 | // redirectWithError flashes a message and redirects, the standard |
| 43 | // Post/Redirect/Get failure path for form submissions. The underlying error is |
| 44 | // logged rather than shown. |
| 45 | func redirectWithError(w http.ResponseWriter, r *http.Request, path, message string, err error) { |
| 46 | if err != nil { |
| 47 | log.Printf("%s %s: %s: %v", r.Method, r.URL.Path, message, err) |
| 48 | } |
| 49 | flashError(w, message) |
| 50 | http.Redirect(w, r, path, http.StatusSeeOther) |
| 51 | } |
| 52 | |
| 53 | // redirectWithSuccess flashes a confirmation and redirects. |
| 54 | func redirectWithSuccess(w http.ResponseWriter, r *http.Request, path, message string) { |
| 55 | flashSuccess(w, message) |
| 56 | http.Redirect(w, r, path, http.StatusSeeOther) |
| 57 | } |
| 58 |