Compare commits

...

5 Commits

12 changed files with 201 additions and 25 deletions

View File

@ -4,6 +4,7 @@ import (
"encoding/gob" "encoding/gob"
"fmt" "fmt"
"go-udemy-web-1/internal/config" "go-udemy-web-1/internal/config"
"go-udemy-web-1/internal/driver"
"go-udemy-web-1/internal/handlers" "go-udemy-web-1/internal/handlers"
"go-udemy-web-1/internal/helpers" "go-udemy-web-1/internal/helpers"
"go-udemy-web-1/internal/models" "go-udemy-web-1/internal/models"
@ -27,10 +28,11 @@ var (
// main is the main application function // main is the main application function
func main() { func main() {
err := run() db, err := run()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
defer db.SQL.Close()
fmt.Printf("Starting application on port %s\n", portNumber) fmt.Printf("Starting application on port %s\n", portNumber)
@ -43,9 +45,12 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
func run() error { func run() (*driver.DB, error) {
// what am I going to put in the session // what am I going to put in the session
gob.Register(models.Reservation{}) gob.Register(models.Reservation{})
gob.Register(models.User{})
gob.Register(models.Room{})
gob.Register(models.Restriction{})
// change this to true when in production // change this to true when in production
app.InProduction = false app.InProduction = false
@ -58,9 +63,19 @@ func run() error {
app.Session = session app.Session = session
// connect to database
log.Println("Connecting to database...")
dsn := fmt.Sprintf("host=localhost port=5432 dbname=test_connect user=%s password=%s", os.Getenv("PGUSER"), os.Getenv("PGPWD"))
db, err := driver.ConnectSQL(dsn)
if err != nil {
log.Fatal("Cannot connect to database! Dying...")
}
log.Println("Connected to database")
tc, err := render.CreateTemplateCache() tc, err := render.CreateTemplateCache()
if err != nil { if err != nil {
log.Fatalf("cannot create template cache: %s", err) log.Fatalf("cannot create template cache: %s", err)
return nil, err
} }
app.TemplateCahce = tc app.TemplateCahce = tc
app.UseCache = false app.UseCache = false
@ -71,10 +86,10 @@ func run() error {
errorLog = log.New(os.Stdout, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile) errorLog = log.New(os.Stdout, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)
app.ErrorLog = errorLog app.ErrorLog = errorLog
repo := handlers.NewRepo(&app) repo := handlers.NewRepo(&app, db)
handlers.NewHandlers(repo) handlers.NewHandlers(repo)
helpers.NewHelpers(&app) helpers.NewHelpers(&app)
render.NewTemplates(&app) render.NewRenderer(&app)
return nil return db, nil
} }

View File

@ -3,7 +3,7 @@ package main
import "testing" import "testing"
func TestRun(t *testing.T) { func TestRun(t *testing.T) {
err := run() _, err := run()
if err != nil { if err != nil {
t.Error("failed run()") t.Error("failed run()")
} }

4
go.mod
View File

@ -3,6 +3,10 @@ module go-udemy-web-1
go 1.21.0 go 1.21.0
// github.com/CloudyKit/jet --> Check this later // github.com/CloudyKit/jet --> Check this later
//
// ORM packages:
// upper/db https://github.com/upper/db
// gorm.io/gorm
require github.com/go-chi/chi/v5 v5.0.14 require github.com/go-chi/chi/v5 v5.0.14

View File

@ -4,11 +4,16 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"go-udemy-web-1/internal/config" "go-udemy-web-1/internal/config"
"go-udemy-web-1/internal/driver"
"go-udemy-web-1/internal/forms" "go-udemy-web-1/internal/forms"
"go-udemy-web-1/internal/helpers" "go-udemy-web-1/internal/helpers"
"go-udemy-web-1/internal/models" "go-udemy-web-1/internal/models"
"go-udemy-web-1/internal/render" "go-udemy-web-1/internal/render"
"go-udemy-web-1/internal/repository"
"go-udemy-web-1/internal/repository/dbrepo"
"net/http" "net/http"
"strconv"
"time"
) )
// Repo the repository used by the handlers // Repo the repository used by the handlers
@ -17,12 +22,14 @@ var Repo *Repository
// Repository is the repository type // Repository is the repository type
type Repository struct { type Repository struct {
App *config.AppConfig App *config.AppConfig
DB repository.DatabaseRepo
} }
// NewRepo creates a new repository // NewRepo creates a new repository
func NewRepo(a *config.AppConfig) *Repository { func NewRepo(a *config.AppConfig, db *driver.DB) *Repository {
return &Repository{ return &Repository{
App: a, App: a,
DB: dbrepo.NewPostgresRepo(db.SQL, a),
} }
} }
@ -33,28 +40,28 @@ func NewHandlers(r *Repository) {
// Home is the home page handler // Home is the home page handler
func (m *Repository) Home(w http.ResponseWriter, r *http.Request) { func (m *Repository) Home(w http.ResponseWriter, r *http.Request) {
render.RenderTemplate(w, r, "home.page.tmpl", &models.TemplateData{}) render.Template(w, r, "home.page.tmpl", &models.TemplateData{})
} }
// About is the about page handler // About is the about page handler
func (m *Repository) About(w http.ResponseWriter, r *http.Request) { func (m *Repository) About(w http.ResponseWriter, r *http.Request) {
// send the data to the template // send the data to the template
render.RenderTemplate(w, r, "about.page.tmpl", &models.TemplateData{}) render.Template(w, r, "about.page.tmpl", &models.TemplateData{})
} }
// Contact is the contact page handler // Contact is the contact page handler
func (m *Repository) Contact(w http.ResponseWriter, r *http.Request) { func (m *Repository) Contact(w http.ResponseWriter, r *http.Request) {
render.RenderTemplate(w, r, "contact.page.tmpl", &models.TemplateData{}) render.Template(w, r, "contact.page.tmpl", &models.TemplateData{})
} }
// Generals is the General's Quarters page handler // Generals is the General's Quarters page handler
func (m *Repository) Generals(w http.ResponseWriter, r *http.Request) { func (m *Repository) Generals(w http.ResponseWriter, r *http.Request) {
render.RenderTemplate(w, r, "generals.page.tmpl", &models.TemplateData{}) render.Template(w, r, "generals.page.tmpl", &models.TemplateData{})
} }
// Majors is the Major's Suite page handler // Majors is the Major's Suite page handler
func (m *Repository) Majors(w http.ResponseWriter, r *http.Request) { func (m *Repository) Majors(w http.ResponseWriter, r *http.Request) {
render.RenderTemplate(w, r, "majors.page.tmpl", &models.TemplateData{}) render.Template(w, r, "majors.page.tmpl", &models.TemplateData{})
} }
// MakeReservation is the make reservation page handler // MakeReservation is the make reservation page handler
@ -66,7 +73,7 @@ func (m *Repository) MakeReservation(w http.ResponseWriter, r *http.Request) {
data["reservation"] = emptyReservation data["reservation"] = emptyReservation
render.RenderTemplate(w, r, "make-reservation.page.tmpl", &models.TemplateData{ render.Template(w, r, "make-reservation.page.tmpl", &models.TemplateData{
Form: forms.New(nil), Form: forms.New(nil),
Data: data, Data: data,
}) })
@ -80,11 +87,33 @@ func (m *Repository) PostMakeReservation(w http.ResponseWriter, r *http.Request)
return return
} }
sd := r.Form.Get("start_date")
ed := r.Form.Get("end_date")
// 2024-07-08 -- 01/02 03:04:05PM '06 -0700
layout := "2006-01-02"
startDate, err := time.Parse(layout, sd)
if err != nil {
helpers.ServerError(w, err)
}
endDate, err := time.Parse(layout, ed)
if err != nil {
helpers.ServerError(w, err)
}
roomId, err := strconv.Atoi(r.Form.Get("room_id"))
if err != nil {
helpers.ServerError(w, err)
}
reservation := models.Reservation{ reservation := models.Reservation{
FirstName: r.Form.Get("first_name"), FirstName: r.Form.Get("first_name"),
LastName: r.Form.Get("last_name"), LastName: r.Form.Get("last_name"),
Email: r.Form.Get("email"), Email: r.Form.Get("email"),
Phone: r.Form.Get("phone"), Phone: r.Form.Get("phone"),
StartDate: startDate,
EndDate: endDate,
RoomID: roomId,
} }
form := forms.New(r.PostForm) form := forms.New(r.PostForm)
@ -97,13 +126,18 @@ func (m *Repository) PostMakeReservation(w http.ResponseWriter, r *http.Request)
data := make(map[string]interface{}) data := make(map[string]interface{})
data["reservation"] = reservation data["reservation"] = reservation
render.RenderTemplate(w, r, "make-reservation.page.tmpl", &models.TemplateData{ render.Template(w, r, "make-reservation.page.tmpl", &models.TemplateData{
Data: data, Data: data,
Form: form, Form: form,
}) })
return return
} }
err = m.DB.InsertReservation(reservation)
if err != nil {
helpers.ServerError(w, err)
}
m.App.Session.Put(r.Context(), "reservation", reservation) m.App.Session.Put(r.Context(), "reservation", reservation)
http.Redirect(w, r, "/reservation-summary", http.StatusSeeOther) http.Redirect(w, r, "/reservation-summary", http.StatusSeeOther)
@ -123,14 +157,14 @@ func (m *Repository) ReservationSummary(w http.ResponseWriter, r *http.Request)
data := make(map[string]interface{}) data := make(map[string]interface{})
data["reservation"] = reservation data["reservation"] = reservation
render.RenderTemplate(w, r, "reservation-summary.page.tmpl", &models.TemplateData{ render.Template(w, r, "reservation-summary.page.tmpl", &models.TemplateData{
Data: data, Data: data,
}) })
} }
// Availability is the search for availability page handler // Availability is the search for availability page handler
func (m *Repository) Availability(w http.ResponseWriter, r *http.Request) { func (m *Repository) Availability(w http.ResponseWriter, r *http.Request) {
render.RenderTemplate(w, r, "availability.page.tmpl", &models.TemplateData{}) render.Template(w, r, "availability.page.tmpl", &models.TemplateData{})
} }
// PostAvailability is the search for availability page handler // PostAvailability is the search for availability page handler

View File

@ -55,7 +55,7 @@ func getRoutes() http.Handler {
repo := NewRepo(&app) repo := NewRepo(&app)
NewHandlers(repo) NewHandlers(repo)
render.NewTemplates(&app) render.NewRenderer(&app)
mux := chi.NewMux() mux := chi.NewMux()

View File

@ -1,9 +1,60 @@
package models package models
// Reservation holds Reservation data import "time"
// User is the user model
type User struct {
CreatedAt time.Time
UpdatedAt time.Time
FirstName string
LastName string
Email string
Password string
ID int
AccessLevel int
}
// Room is the room model
type Room struct {
CreatedAt time.Time
UpdatedAt time.Time
RoomName string
ID int
}
// Restriction is the restriction model
type Restriction struct {
CreatedAt time.Time
UpdatedAt time.Time
RestrictionName string
ID int
}
// Reservation is the reservation model
type Reservation struct { type Reservation struct {
CreatedAt time.Time
UpdatedAt time.Time
StartDate time.Time
EndDate time.Time
FirstName string FirstName string
LastName string LastName string
Email string Email string
Phone string Phone string
Room Room
ID int
RoomID int
}
// RoomRestriction is the room restriction model
type RoomRestriction struct {
StartDate time.Time
EndDate time.Time
CreatedAt time.Time
UpdatedAt time.Time
Room Room
Restriction Restriction
ID int
RoomID int
ReservationId int
RestrictionID int
} }

View File

@ -21,8 +21,8 @@ var (
pathToTemplates = "./templates" pathToTemplates = "./templates"
) )
// NewTemplates sets the config for the template package // NewRenderer sets the config for the template package
func NewTemplates(a *config.AppConfig) { func NewRenderer(a *config.AppConfig) {
app = a app = a
} }
@ -35,8 +35,8 @@ func AddDefaultData(td *models.TemplateData, r *http.Request) *models.TemplateDa
return td return td
} }
// RenderTemplate renders a HTML template file // Template renders a HTML template file
func RenderTemplate(w http.ResponseWriter, r *http.Request, tmpl string, td *models.TemplateData) error { func Template(w http.ResponseWriter, r *http.Request, tmpl string, td *models.TemplateData) error {
var tc map[string]*template.Template var tc map[string]*template.Template
if app.UseCache { if app.UseCache {
// get the template cache from the app config // get the template cache from the app config

View File

@ -39,12 +39,12 @@ func TestRenderTemplate(t *testing.T) {
var ww myWriter var ww myWriter
err = RenderTemplate(&ww, r, "home.page.tmpl", &models.TemplateData{}) err = Template(&ww, r, "home.page.tmpl", &models.TemplateData{})
if err != nil { if err != nil {
t.Error("error writiing template to browser") t.Error("error writiing template to browser")
} }
err = RenderTemplate(&ww, r, "non-existent.page.html", &models.TemplateData{}) err = Template(&ww, r, "non-existent.page.html", &models.TemplateData{})
if err == nil { if err == nil {
t.Error("rendered template that doesn't exist") t.Error("rendered template that doesn't exist")
} }
@ -64,7 +64,7 @@ func getSession() (*http.Request, error) {
} }
func TestNewTemplate(t *testing.T) { func TestNewTemplate(t *testing.T) {
NewTemplates(app) NewRenderer(app)
} }
func TestCreateTemplateCache(t *testing.T) { func TestCreateTemplateCache(t *testing.T) {

View File

@ -0,0 +1,19 @@
package dbrepo
import (
"database/sql"
"go-udemy-web-1/internal/config"
"go-udemy-web-1/internal/repository"
)
type postgresDBRepo struct {
App *config.AppConfig
DB *sql.DB
}
func NewPostgresRepo(conn *sql.DB, a *config.AppConfig) repository.DatabaseRepo {
return &postgresDBRepo{
App: a,
DB: conn,
}
}

View File

@ -0,0 +1,29 @@
package dbrepo
import (
"context"
"go-udemy-web-1/internal/models"
"time"
)
func (m *postgresDBRepo) AllUsers() bool {
return true
}
// InsertReservation inserts a reservation into the database
func (m *postgresDBRepo) InsertReservation(res models.Reservation) error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// statement
stmt := `insert into reservations (first_name, last_name, email, phone,
start_date, end_date, room_id, created_at, updated_at)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9)`
_, err := m.DB.ExecContext(ctx, stmt, res.FirstName, res.LastName, res.Email, res.Phone,
res.StartDate, res.EndDate, res.RoomID, res.CreatedAt, res.UpdatedAt)
if err != nil {
return err
}
return nil
}

View File

@ -0,0 +1,9 @@
package repository
import "go-udemy-web-1/internal/models"
type DatabaseRepo interface {
AllUsers() bool
InsertReservation(res models.Reservation) error
}

View File

@ -26,6 +26,21 @@
<input type="text" name="last_name" id="last_name" class="form-control {{with .Form.Errors.Get "last_name"}} is-invalid {{end}}" <input type="text" name="last_name" id="last_name" class="form-control {{with .Form.Errors.Get "last_name"}} is-invalid {{end}}"
value="{{$res.LastName}}" required autocomplete="off"> value="{{$res.LastName}}" required autocomplete="off">
</div> </div>
<div class="form-group mt-5">
<label for="start_date">Start date:</label>
<input type="text" name="start_date" id="start_date" class="form-control"
required autocomplete="off">
</div>
<div class="form-group mt-5">
<label for="end_date">End date:</label>
<input type="text" name="end_date" id="end_date" class="form-control"
required autocomplete="off">
</div>
<input type="hidden" name="room_id" value="1">
<div class="form-group mt-5"> <div class="form-group mt-5">
<label for="email">Email:</label> <label for="email">Email:</label>
{{with .Form.Errors.Get "email"}} {{with .Form.Errors.Get "email"}}