Centralizing error handling to a helpers package

This commit is contained in:
Muyao CHEN
2024-07-03 10:03:25 +02:00
parent 0c0159734e
commit 9fc6c05d38
7 changed files with 65 additions and 20 deletions

View File

@ -5,9 +5,9 @@ import (
"fmt"
"go-udemy-web-1/internal/config"
"go-udemy-web-1/internal/forms"
"go-udemy-web-1/internal/helpers"
"go-udemy-web-1/internal/models"
"go-udemy-web-1/internal/render"
"log"
"net/http"
)
@ -33,23 +33,13 @@ func NewHandlers(r *Repository) {
// Home is the home page handler
func (m *Repository) Home(w http.ResponseWriter, r *http.Request) {
remoteIP := r.RemoteAddr
m.App.Session.Put(r.Context(), "remote_ip", remoteIP)
render.RenderTemplate(w, r, "home.page.tmpl", &models.TemplateData{})
}
// About is the about page handler
func (m *Repository) About(w http.ResponseWriter, r *http.Request) {
// perform some logic
stringMap := make(map[string]string)
stringMap["test"] = "Hello world!"
remoteIP := m.App.Session.GetString(r.Context(), "remote_ip")
stringMap["remote_ip"] = remoteIP
// send the data to the template
render.RenderTemplate(w, r, "about.page.tmpl", &models.TemplateData{StringMap: stringMap})
render.RenderTemplate(w, r, "about.page.tmpl", &models.TemplateData{})
}
// Contact is the contact page handler
@ -86,7 +76,7 @@ func (m *Repository) MakeReservation(w http.ResponseWriter, r *http.Request) {
func (m *Repository) PostMakeReservation(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
log.Println(err)
helpers.ServerError(w, err)
return
}
@ -123,7 +113,7 @@ func (m *Repository) PostMakeReservation(w http.ResponseWriter, r *http.Request)
func (m *Repository) ReservationSummary(w http.ResponseWriter, r *http.Request) {
reservation, ok := m.App.Session.Get(r.Context(), "reservation").(models.Reservation)
if !ok {
log.Println("connot get item from reservation")
m.App.ErrorLog.Println("connot get item from session")
m.App.Session.Put(r.Context(), "error", "Can't get reservation from session")
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}
@ -164,7 +154,8 @@ func (m *Repository) AvailabilityJSON(w http.ResponseWriter, r *http.Request) {
out, err := json.MarshalIndent(resp, "", " ")
if err != nil {
log.Println(err)
helpers.ServerError(w, err)
return
}
w.Header().Set("Content-Type", "application/json")

View File

@ -9,6 +9,7 @@ import (
"html/template"
"log"
"net/http"
"os"
"path/filepath"
"time"
@ -45,6 +46,12 @@ func getRoutes() http.Handler {
app.TemplateCahce = tc
app.UseCache = true // Not to use ./templates
infoLog := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)
app.InfoLog = infoLog
errorLog := log.New(os.Stdout, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)
app.ErrorLog = errorLog
repo := NewRepo(&app)
NewHandlers(repo)