summaryrefslogtreecommitdiff
path: root/server.go
diff options
context:
space:
mode:
authorxengineering <me@xengineering.eu>2023-04-25 17:39:48 +0200
committerxengineering <me@xengineering.eu>2023-04-28 10:44:29 +0200
commitf456fa1a6d3a6633af3b420f1eddbc1a96ffcdf1 (patch)
tree6803e98d6370abf887301adaf26438000fa7c292 /server.go
parentfff3d70ba494214e434083c9d0e32f3def32138f (diff)
downloadceres-f456fa1a6d3a6633af3b420f1eddbc1a96ffcdf1.tar
ceres-f456fa1a6d3a6633af3b420f1eddbc1a96ffcdf1.tar.zst
ceres-f456fa1a6d3a6633af3b420f1eddbc1a96ffcdf1.zip
Introduce routing table
This removes a lot of repetative code.
Diffstat (limited to 'server.go')
-rw-r--r--server.go45
1 files changed, 32 insertions, 13 deletions
diff --git a/server.go b/server.go
index 891a7b9..3c82f36 100644
--- a/server.go
+++ b/server.go
@@ -3,23 +3,42 @@ package main
import (
"log"
"net/http"
+ "strings"
)
-func setupRoutes() {
-
- http.HandleFunc("/", indexMux)
- http.HandleFunc("/recipe", recipeMux)
- http.HandleFunc("/recipe/edit", recipeEditMux)
- http.HandleFunc("/recipe/confirm-deletion", recipeConfirmDeletionMux)
- http.HandleFunc("/add_recipes", addRecipesMux)
- http.HandleFunc("/static/style.css", staticStyleMux)
- http.HandleFunc("/favicon.ico", faviconMux)
-}
-
func runServer() {
-
- setupRoutes()
address := config.Host + ":" + config.Port
+ http.HandleFunc("/", route)
log.Println("Serving content at 'http://" + address + "'.")
log.Fatal(http.ListenAndServe(address, nil))
}
+
+func route(w http.ResponseWriter, r *http.Request) {
+
+ tab := routingTable{
+ {"/favicon.ico", "GET", staticGet("favicon.ico")},
+ {"/static/style.css", "GET", staticGet("style.css")},
+ {"/add_recipes", "GET", addRecipesGet},
+ {"/recipe/confirm-deletion", "GET", recipeConfirmDeletionGet},
+ {"/recipe/confirm-deletion", "POST", recipeConfirmDeletionPost},
+ {"/recipe/edit", "GET", recipeEditGet},
+ {"/recipe/edit", "POST", recipeEditPost},
+ {"/recipe", "GET", recipeGet},
+ {"/", "GET", indexGet},
+ }
+
+ for _, v := range(tab) {
+ if strings.HasPrefix(r.URL.String(), v.target) && r.Method == v.method {
+ v.handler(w, r)
+ return
+ }
+ }
+
+ http.Error(w, "Bad Request", 400)
+}
+
+type routingTable []struct {
+ target string
+ method string
+ handler func(w http.ResponseWriter, r *http.Request)
+}