2018-10-25 18:06:54 +02:00
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"html/template"
|
2018-10-26 10:40:11 +02:00
|
|
|
"strconv"
|
2018-10-25 18:06:54 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type Page struct {
|
|
|
|
Path string
|
|
|
|
Template string
|
|
|
|
Data map[string]interface{}
|
2018-10-26 10:40:11 +02:00
|
|
|
DynamicDataLoader func(int) map[string]interface{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func DynamicDataLoaderCategory(id int) map[string]interface{}{
|
|
|
|
return map[string]interface{}{
|
|
|
|
"category": GetCategoryById(id),
|
|
|
|
"products": GetCategoryProducts(id),
|
|
|
|
}
|
2018-10-25 18:06:54 +02:00
|
|
|
}
|
|
|
|
|
2018-10-26 17:53:00 +02:00
|
|
|
func DynamicDataLoaderProduct(id int) map[string]interface{}{
|
|
|
|
return map[string]interface{}{
|
|
|
|
"product": GetProductById(id),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-25 18:06:54 +02:00
|
|
|
func (p Page) HandlePage(w http.ResponseWriter, r *http.Request) {
|
2018-10-26 10:40:11 +02:00
|
|
|
if p.DynamicDataLoader != nil {
|
|
|
|
id, err := strconv.Atoi(r.URL.Query()["id"][0])
|
|
|
|
if err == nil {
|
|
|
|
p.Data = p.DynamicDataLoader(id)
|
|
|
|
}
|
|
|
|
}
|
2018-10-25 20:09:08 +02:00
|
|
|
t, _ := template.ParseFiles(p.Template, "templates/base.html")
|
|
|
|
t.ExecuteTemplate(w, "base", p.Data)
|
2018-10-25 18:06:54 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type Category struct {
|
2018-10-26 10:40:11 +02:00
|
|
|
Id int
|
2018-10-25 18:06:54 +02:00
|
|
|
Name string
|
|
|
|
}
|
|
|
|
|
|
|
|
type Product struct {
|
2018-10-26 10:40:11 +02:00
|
|
|
Id int
|
2018-10-25 18:06:54 +02:00
|
|
|
Category Category
|
|
|
|
Name string
|
|
|
|
Description string
|
|
|
|
ImgUrl string
|
|
|
|
Quantity uint
|
|
|
|
Price uint
|
|
|
|
}
|
|
|
|
|
|
|
|
var Pages map[string]Page
|
|
|
|
var Categories []Category
|
|
|
|
var Products []Product
|
2018-10-25 20:09:08 +02:00
|
|
|
|
|
|
|
func GetCategoryByName(name string) Category {
|
|
|
|
var category Category
|
|
|
|
for i:= range Categories {
|
|
|
|
if Categories[i].Name == name {
|
|
|
|
category = Categories[i]
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return category
|
|
|
|
}
|
2018-10-26 10:40:11 +02:00
|
|
|
|
|
|
|
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])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return products
|
|
|
|
}
|
2018-10-26 17:53:00 +02:00
|
|
|
|
|
|
|
func GetProductById(id int) Product {
|
|
|
|
var product Product
|
|
|
|
for i:= range Products {
|
|
|
|
if Products[i].Id == id {
|
|
|
|
product = Products[i]
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return product
|
|
|
|
}
|