lets-go:2.6 refactor app to go "Developing Modules" pattern

https://go.dev/doc/modules/layout#server-project
This commit is contained in:
tamsin johnson 2024-01-22 15:07:14 -08:00
parent cb0a335636
commit 79c2b58f6a
2 changed files with 27 additions and 14 deletions

View File

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

View File

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