ch3.4
This commit is contained in:
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
func (app *application) home(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/" {
|
||||
http.NotFound(w, r)
|
||||
app.notFound(w)
|
||||
return
|
||||
}
|
||||
files := []string{
|
||||
@@ -19,21 +19,19 @@ func (app *application) home(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
ts, err := template.ParseFiles(files...)
|
||||
if err != nil {
|
||||
app.errorLog.Print(err.Error())
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
app.serverError(w, err)
|
||||
return
|
||||
}
|
||||
err = ts.ExecuteTemplate(w, "base", nil)
|
||||
if err != nil {
|
||||
app.errorLog.Print(err.Error())
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
app.serverError(w, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (app *application) 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)
|
||||
app.notFound(w)
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(w, "Display a specific snippet with ID %d...", id)
|
||||
@@ -42,7 +40,7 @@ func (app *application) snippetView(w http.ResponseWriter, r *http.Request) {
|
||||
func (app *application) snippetCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
w.Header().Set("Allow", http.MethodPost)
|
||||
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
|
||||
app.clientError(w, http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
w.Write([]byte("Create a new snippet"))
|
||||
|
||||
22
cmd/web/helpers.go
Normal file
22
cmd/web/helpers.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
)
|
||||
|
||||
func (app *application) serverError(w http.ResponseWriter, err error) {
|
||||
trace := fmt.Sprintf("%s\n%s", err.Error(), debug.Stack())
|
||||
app.errorLog.Output(2, trace)
|
||||
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
func (app *application) clientError(w http.ResponseWriter, status int) {
|
||||
http.Error(w, http.StatusText(status), status)
|
||||
}
|
||||
|
||||
func (app *application) notFound(w http.ResponseWriter) {
|
||||
app.clientError(w, http.StatusNotFound)
|
||||
}
|
||||
Reference in New Issue
Block a user