From 30976a55e8ac27e132b64467c02f7f3e839caa03 Mon Sep 17 00:00:00 2001 From: vinchent Date: Tue, 6 Aug 2024 14:10:25 +0200 Subject: [PATCH] Create models and modify the handler to take a struct --- cmd/web/handlers.go | 16 +++++++++++++++- internal/models/models.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 internal/models/models.go diff --git a/cmd/web/handlers.go b/cmd/web/handlers.go index 705e7f5..68ca7e9 100644 --- a/cmd/web/handlers.go +++ b/cmd/web/handlers.go @@ -1,6 +1,7 @@ package main import ( + "myapp/internal/models" "net/http" ) @@ -46,7 +47,20 @@ func (app *application) PaymentSucceeded(w http.ResponseWriter, r *http.Request) // ChargeOnce displays the page to buy one widget func (app *application) ChargeOnce(w http.ResponseWriter, r *http.Request) { - if err := app.renderTemplate(w, r, "buy-once", nil, "stripe-js"); err != nil { + widget := models.Widget{ + ID: 1, + Name: "Custom Widget", + Description: "Paris 2024", + InventoryLevel: 10, + Price: 1000, + } + + data := make(map[string]interface{}) + data["widget"] = widget + + if err := app.renderTemplate(w, r, "buy-once", &templateData{ + Data: data, + }, "stripe-js"); err != nil { app.errorLog.Println(err) } } diff --git a/internal/models/models.go b/internal/models/models.go new file mode 100644 index 0000000..7507bfd --- /dev/null +++ b/internal/models/models.go @@ -0,0 +1,34 @@ +package models + +import ( + "database/sql" + "time" +) + +// DBModel is the type for database connection values +type DBModel struct { + DB *sql.DB +} + +// Models is the wrapper for all models +type Models struct { + DB DBModel +} + +// NewModels returns a model type with database connection pool +func NewModels(db *sql.DB) Models { + return Models{ + DB: DBModel{DB: db}, + } +} + +// Widget is the type for all widgets +type Widget struct { + ID int `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + InventoryLevel int `json:"inventory_level"` + Price int `json:"price"` + CreatedAt time.Time `json:"-"` + UpdatedAt time.Time `json:"-"` +}