From 79c2b58f6a82d76b26af2734496614d56da3d019 Mon Sep 17 00:00:00 2001 From: tamsin johnson Date: Mon, 22 Jan 2024 15:07:14 -0800 Subject: [PATCH] lets-go:2.6 refactor app to go "Developing Modules" pattern https://go.dev/doc/modules/layout#server-project --- snippetbox/{main.go => cmd/web/handlers.go} | 23 ++++++++------------- snippetbox/cmd/web/main.go | 18 ++++++++++++++++ 2 files changed, 27 insertions(+), 14 deletions(-) rename snippetbox/{main.go => cmd/web/handlers.go} (62%) create mode 100644 snippetbox/cmd/web/main.go diff --git a/snippetbox/main.go b/snippetbox/cmd/web/handlers.go similarity index 62% rename from snippetbox/main.go rename to snippetbox/cmd/web/handlers.go index fd26685..debf020 100644 --- a/snippetbox/main.go +++ b/snippetbox/cmd/web/handlers.go @@ -1,8 +1,9 @@ package main import ( - "log" + "fmt" "net/http" + "strconv" ) // home ... @@ -16,7 +17,13 @@ func home(w http.ResponseWriter, r *http.Request) { // snippetView ... func snippetView(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("It's a snippet!")) + id, err := strconv.Atoi(r.URL.Query().Get("id")) + if err != nil || id < 1 { + http.NotFound(w, r) + return + } + + fmt.Fprintf(w, "It's snippet id: %d", id) } // snippetCreate ... @@ -30,15 +37,3 @@ func snippetCreate(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Creating a snippet!")) } - -// main it's the snippetbox webapp -func main() { - mux := http.NewServeMux() - mux.HandleFunc("/", home) - mux.HandleFunc("/snippet/view", snippetView) - mux.HandleFunc("/snippet/create", snippetCreate) - - log.Print("starting a server on :4000") - err := http.ListenAndServe(":4000", mux) - log.Fatal(err) -} diff --git a/snippetbox/cmd/web/main.go b/snippetbox/cmd/web/main.go new file mode 100644 index 0000000..0c4da5d --- /dev/null +++ b/snippetbox/cmd/web/main.go @@ -0,0 +1,18 @@ +package main + +import ( + "log" + "net/http" +) + +// main it's the snippetbox webapp +func main() { + mux := http.NewServeMux() + mux.HandleFunc("/", home) + mux.HandleFunc("/snippet/view", snippetView) + mux.HandleFunc("/snippet/create", snippetCreate) + + log.Print("starting a server on :4000") + err := http.ListenAndServe(":4000", mux) + log.Fatal(err) +}