Switch to Chi router

This commit is contained in:
Lucas Schumacher 2024-07-31 17:21:57 -04:00
parent 2d2bea6543
commit d1cd20225b
3 changed files with 16 additions and 18 deletions

2
go.mod
View File

@ -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

2
go.sum Normal file
View File

@ -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=

24
main.go
View File

@ -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:
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")
}
fmt.Fprintf(w, "<hr><p>%s</p>", r.URL.Path)
}
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)
}