From 975654539fba776abeccb581f3211fd5bb59f038 Mon Sep 17 00:00:00 2001 From: Eduardo Silva Date: Mon, 10 Jun 2024 12:24:01 +0100 Subject: [PATCH] Made the server functions use switch statements Also removed the now unecessary checkMethod function --- src/server/server.go | 46 ++++++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/src/server/server.go b/src/server/server.go index 41743ac..bebc541 100644 --- a/src/server/server.go +++ b/src/server/server.go @@ -6,48 +6,46 @@ import ( "thermalFax/controllers" ) -func checkMethod(method string, r *http.Request) bool { - return r.Method == method -} - func Serve() { // GET calls http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - if !checkMethod(http.MethodGet, r) { + switch r.Method { + case http.MethodGet: + // We redirect to the editor page, if the user is logged in he can fire a fax right away + // Otherwise it just redirects him to the login page anyway + http.Redirect(w, r, "/editor", http.StatusPermanentRedirect) + default: w.WriteHeader(http.StatusMethodNotAllowed) - return } - - http.Redirect(w, r, "/login", http.StatusPermanentRedirect) - // controllers.Editor(w, r) }) http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) { - if !checkMethod(http.MethodGet, r) { + switch r.Method { + case http.MethodGet: + controllers.Login(w, r) + default: w.WriteHeader(http.StatusMethodNotAllowed) - return } - - controllers.Editor(w, r) }) // POST calls http.HandleFunc("/send-fax", func(w http.ResponseWriter, r *http.Request) { - if !checkMethod(http.MethodPost, r) { + switch r.Method { + case http.MethodPost: + controllers.SendFax(w, r) + default: w.WriteHeader(http.StatusMethodNotAllowed) - return } - - controllers.SendFax(w, r) }) + // Move this into the /login endpoint but as POST instead http.HandleFunc("/send-login", func(w http.ResponseWriter, r *http.Request) { - if !checkMethod(http.MethodPost, r) { + switch r.Method { + case http.MethodPost: + controllers.Authenticate(w, r) + default: w.WriteHeader(http.StatusMethodNotAllowed) - return } - - controllers.Authenticate(w, r) }) // Pages @@ -58,6 +56,8 @@ func Serve() { controllers.HistoryPOST(w, r) case http.MethodGet: controllers.History(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) } }) @@ -67,6 +67,8 @@ func Serve() { controllers.EditorPOST(w, r) case http.MethodGet: controllers.Editor(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) } }) @@ -76,6 +78,8 @@ func Serve() { controllers.PersonalDataPOST(w, r) case http.MethodGet: controllers.PersonalData(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) } })