Create models and modify the handler to take a struct

This commit is contained in:
vinchent 2024-08-06 14:10:25 +02:00
parent 7e0df51d88
commit 30976a55e8
2 changed files with 49 additions and 1 deletions

View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"myapp/internal/models"
"net/http" "net/http"
) )
@ -46,7 +47,20 @@ func (app *application) PaymentSucceeded(w http.ResponseWriter, r *http.Request)
// ChargeOnce displays the page to buy one widget // ChargeOnce displays the page to buy one widget
func (app *application) ChargeOnce(w http.ResponseWriter, r *http.Request) { 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) app.errorLog.Println(err)
} }
} }

34
internal/models/models.go Normal file
View File

@ -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:"-"`
}