Elektromarket/models/models.go

85 lines
1.5 KiB
Go

package models
import (
"net/http"
"html/template"
"strconv"
)
type Page struct {
Path string
Template string
Data map[string]interface{}
DynamicDataLoader func(int) map[string]interface{}
}
func DynamicDataLoaderCategory(id int) map[string]interface{}{
return map[string]interface{}{
"category": GetCategoryById(id),
"products": GetCategoryProducts(id),
}
}
func (p Page) HandlePage(w http.ResponseWriter, r *http.Request) {
if p.DynamicDataLoader != nil {
id, err := strconv.Atoi(r.URL.Query()["id"][0])
if err == nil {
p.Data = p.DynamicDataLoader(id)
}
}
t, _ := template.ParseFiles(p.Template, "templates/base.html")
t.ExecuteTemplate(w, "base", p.Data)
}
type Category struct {
Id int
Name string
}
type Product struct {
Id int
Category Category
Name string
Description string
ImgUrl string
Quantity uint
Price uint
}
var Pages map[string]Page
var Categories []Category
var Products []Product
func GetCategoryByName(name string) Category {
var category Category
for i:= range Categories {
if Categories[i].Name == name {
category = Categories[i]
break
}
}
return category
}
func GetCategoryById(id int) Category {
var category Category
for i:= range Categories {
if Categories[i].Id == id {
category = Categories[i]
break
}
}
return category
}
func GetCategoryProducts(id int) []Product {
var products []Product
for i:= range Products {
if Products[i].Category.Id == id {
products = append(products, Products[i])
break
}
}
return products
}