more work starting 2.9
This commit is contained in:
49
snippetbox/cmd/web/handlers.go
Normal file
49
snippetbox/cmd/web/handlers.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func home(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
files := []string{
|
||||
"./ui/html/base.tmpl",
|
||||
"./ui/html/partials/nav.tmpl",
|
||||
"./ui/html/pages/home.tmpl",
|
||||
}
|
||||
ts, err := template.ParseFiles(files...)
|
||||
if err != nil {
|
||||
log.Print(err.Error())
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
err = ts.ExecuteTemplate(w, "base", nil)
|
||||
if err != nil {
|
||||
log.Print(err.Error())
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func snippetView(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.Atoi(r.URL.Query().Get("id"))
|
||||
if err != nil || id < 1 {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(w, "Display a specific snippet with ID %d...", id)
|
||||
}
|
||||
func snippetCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "POST" {
|
||||
w.Header().Set("Allow", http.MethodPost)
|
||||
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
w.Write([]byte("Create a new snippet"))
|
||||
}
|
||||
18
snippetbox/cmd/web/main.go
Normal file
18
snippetbox/cmd/web/main.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func main() {
|
||||
mux := http.NewServeMux()
|
||||
fileServer := http.FileServer(http.Dir("./ui/static/"))
|
||||
mux.Handle("/static/", http.StripPrefix("/static", fileServer))
|
||||
mux.HandleFunc("/", home)
|
||||
mux.HandleFunc("/snippet/view", snippetView)
|
||||
mux.HandleFunc("/snippet/create", snippetCreate)
|
||||
log.Print("Starting server on :4000")
|
||||
err := http.ListenAndServe(":4000", mux)
|
||||
log.Fatal(err)
|
||||
}
|
||||
Reference in New Issue
Block a user