Refactor: Fetch handler to return status code

This commit is contained in:
bronku 2025-03-22 23:53:38 +01:00
parent a7bd1478bf
commit 47323b32f8
4 changed files with 13 additions and 12 deletions

View file

@ -2,4 +2,4 @@ package server
import "net/http" import "net/http"
type fetcher func(r *http.Request) (any, error) type fetcher func(r *http.Request) (any, int, error)

View file

@ -8,11 +8,12 @@ import (
"github.com/Bronku/iroon/store" "github.com/Bronku/iroon/store"
) )
func (h *Server) index(r *http.Request) (any, error) { func (h *Server) index(r *http.Request) (any, int, error) {
return h.s.GetOrders() data, err := h.s.GetOrders()
return data, http.StatusOK, err
} }
func (h *Server) order(r *http.Request) (any, error) { func (h *Server) getOrder(r *http.Request) (any, int, error) {
type formData struct { type formData struct {
Order store.Order Order store.Order
Catalogue []store.Cake Catalogue []store.Cake
@ -22,23 +23,23 @@ func (h *Server) order(r *http.Request) (any, error) {
data.Catalogue, err = h.s.GetCakes() data.Catalogue, err = h.s.GetCakes()
if err != nil { if err != nil {
return nil, err return nil, http.StatusInternalServerError, err
} }
url := strings.Split(r.URL.String(), "/") url := strings.Split(r.URL.String(), "/")
if len(url) < 3 || url[2] == "" { if len(url) < 3 || url[2] == "" {
return data, nil return data, http.StatusOK, nil
} }
id, err := strconv.Atoi(url[2]) id, err := strconv.Atoi(url[2])
if err != nil { if err != nil {
return nil, err return nil, http.StatusBadRequest, err
} }
data.Order, err = h.s.GetOrder(id) data.Order, err = h.s.GetOrder(id)
if err != nil { if err != nil {
return nil, err return nil, http.StatusNotFound, err
} }
return data, nil return data, http.StatusOK, nil
} }

View file

@ -31,7 +31,7 @@ func (h *Server) openStore() error {
func (h *Server) loadHandler() { func (h *Server) loadHandler() {
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("GET /order/", h.render(h.order, "order.html")) mux.HandleFunc("GET /order/", h.render(h.getOrder, "order.html"))
mux.HandleFunc("GET /", h.render(h.index, "index.html")) mux.HandleFunc("GET /", h.render(h.index, "index.html"))
mux.HandleFunc("POST /order/", h.postOrder) mux.HandleFunc("POST /order/", h.postOrder)

View file

@ -18,9 +18,9 @@ func (h *Server) loadTemplates() error {
func (s *Server) render(fetch fetcher, templateName string) http.HandlerFunc { func (s *Server) render(fetch fetcher, templateName string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "text/html") w.Header().Set("content-type", "text/html")
data, err := fetch(r) data, code, err := fetch(r)
if err != nil { if err != nil {
errorPage(err, http.StatusInternalServerError).ServeHTTP(w, r) errorPage(err, code).ServeHTTP(w, r)
return return
} }
err = s.tmpl.ExecuteTemplate(w, templateName, data) err = s.tmpl.ExecuteTemplate(w, templateName, data)