From d1cd20225b417542a5d4926cb84dd1de4e6d88da Mon Sep 17 00:00:00 2001 From: Lucas Schumacher Date: Wed, 31 Jul 2024 17:21:57 -0400 Subject: [PATCH] Switch to Chi router --- go.mod | 2 ++ go.sum | 2 ++ main.go | 30 ++++++++++++------------------ 3 files changed, 16 insertions(+), 18 deletions(-) create mode 100644 go.sum diff --git a/go.mod b/go.mod index 73280be..012ea5f 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module git.kealoha.me/lks/lenslocked go 1.22.5 + +require github.com/go-chi/chi/v5 v5.1.0 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..823cdbb --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw= +github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= diff --git a/main.go b/main.go index c895d4a..df3b7a1 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,8 @@ package main import ( "fmt" "net/http" + + "github.com/go-chi/chi/v5" ) func homeHandler(w http.ResponseWriter, r *http.Request) { @@ -25,26 +27,18 @@ func faqHandler(w http.ResponseWriter, r *http.Request) { `) } -type Router struct{} - -func (router Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/": - homeHandler(w, r) - case "/contact": - contactHandler(w, r) - case "/faq": - faqHandler(w, r) - default: - w.Header().Set("Content-Type", "text/html; charset=utf8") - w.WriteHeader(http.StatusNotFound) - fmt.Fprint(w, "404 page not found") - } - fmt.Fprintf(w, "

%s

", r.URL.Path) +func notFoundHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf8") + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, "404 page not found") } func main() { - var router Router + r := chi.NewRouter() + r.Get("/", homeHandler) + r.Get("/contact", contactHandler) + r.Get("/faq", faqHandler) + r.NotFound(notFoundHandler) fmt.Println("Starting the server on :3000...") - http.ListenAndServe(":3000", router) + http.ListenAndServe(":3000", r) }