Refactor and remove sqlite and replace with MySQL
This commit is contained in:
151
internal/helpers/template/build.go
Normal file
151
internal/helpers/template/build.go
Normal file
@@ -0,0 +1,151 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"synlotto-website/config"
|
||||
helpers "synlotto-website/helpers/http"
|
||||
"synlotto-website/models"
|
||||
|
||||
"github.com/gorilla/csrf"
|
||||
)
|
||||
|
||||
func TemplateContext(w http.ResponseWriter, r *http.Request, data models.TemplateData) map[string]interface{} {
|
||||
cfg := config.Get()
|
||||
if cfg == nil {
|
||||
log.Println("⚠️ Config not initialized!")
|
||||
}
|
||||
session, _ := helpers.GetSession(w, r)
|
||||
|
||||
var flash string
|
||||
if f, ok := session.Values["flash"].(string); ok {
|
||||
flash = f
|
||||
delete(session.Values, "flash")
|
||||
session.Save(r, w)
|
||||
}
|
||||
|
||||
return map[string]interface{}{
|
||||
"CSRFField": csrf.TemplateField(r),
|
||||
"Flash": flash,
|
||||
"User": data.User,
|
||||
"IsAdmin": data.IsAdmin,
|
||||
"NotificationCount": data.NotificationCount,
|
||||
"Notifications": data.Notifications,
|
||||
"MessageCount": data.MessageCount,
|
||||
"Messages": data.Messages,
|
||||
"SiteName": cfg.Site.SiteName,
|
||||
"CopyrightYearStart": cfg.Site.CopyrightYearStart,
|
||||
}
|
||||
}
|
||||
|
||||
func TemplateFuncs() template.FuncMap {
|
||||
return template.FuncMap{
|
||||
"plus1": func(i int) int { return i + 1 },
|
||||
"minus1": func(i int) int {
|
||||
if i > 1 {
|
||||
return i - 1
|
||||
}
|
||||
return 0
|
||||
},
|
||||
"mul": func(a, b int) int { return a * b },
|
||||
"add": func(a, b int) int { return a + b },
|
||||
"sub": func(a, b int) int { return a - b },
|
||||
"min": func(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
} else {
|
||||
return b
|
||||
}
|
||||
},
|
||||
"intVal": func(p *int) int {
|
||||
if p == nil {
|
||||
return 0
|
||||
}
|
||||
return *p
|
||||
},
|
||||
"inSlice": InSlice,
|
||||
"lower": lower,
|
||||
"truncate": func(s string, max int) string {
|
||||
if len(s) <= max {
|
||||
return s
|
||||
}
|
||||
return s[:max] + "..."
|
||||
},
|
||||
"PageRange": PageRange,
|
||||
"now": time.Now,
|
||||
"humanTime": func(v interface{}) string {
|
||||
switch t := v.(type) {
|
||||
case time.Time:
|
||||
return t.Local().Format("02 Jan 2006 15:04")
|
||||
case string:
|
||||
parsed, err := time.Parse(time.RFC3339, t)
|
||||
if err == nil {
|
||||
return parsed.Local().Format("02 Jan 2006 15:04")
|
||||
}
|
||||
return t
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
},
|
||||
"rangeClass": rangeClass,
|
||||
}
|
||||
}
|
||||
|
||||
func LoadTemplateFiles(name string, files ...string) *template.Template {
|
||||
shared := []string{
|
||||
"templates/main/layout.html",
|
||||
"templates/main/topbar.html",
|
||||
"templates/main/footer.html",
|
||||
}
|
||||
all := append(shared, files...)
|
||||
|
||||
return template.Must(template.New(name).Funcs(TemplateFuncs()).ParseFiles(all...))
|
||||
}
|
||||
|
||||
func SetFlash(w http.ResponseWriter, r *http.Request, message string) {
|
||||
session, _ := helpers.GetSession(w, r)
|
||||
session.Values["flash"] = message
|
||||
session.Save(r, w)
|
||||
}
|
||||
|
||||
func InSlice(n int, list []int) bool {
|
||||
for _, v := range list {
|
||||
if v == n {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func lower(input string) string {
|
||||
return strings.ToLower(input)
|
||||
}
|
||||
|
||||
func PageRange(current, total int) []int {
|
||||
var pages []int
|
||||
for i := 1; i <= total; i++ {
|
||||
pages = append(pages, i)
|
||||
}
|
||||
return pages
|
||||
}
|
||||
|
||||
func rangeClass(n int) string {
|
||||
switch {
|
||||
case n >= 1 && n <= 9:
|
||||
return "01-09"
|
||||
case n >= 10 && n <= 19:
|
||||
return "10-19"
|
||||
case n >= 20 && n <= 29:
|
||||
return "20-29"
|
||||
case n >= 30 && n <= 39:
|
||||
return "30-39"
|
||||
case n >= 40 && n <= 49:
|
||||
return "40-49"
|
||||
default:
|
||||
return "50-plus"
|
||||
}
|
||||
}
|
||||
39
internal/helpers/template/error.go
Normal file
39
internal/helpers/template/error.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"synlotto-website/models"
|
||||
)
|
||||
|
||||
func RenderError(w http.ResponseWriter, r *http.Request, statusCode int) {
|
||||
log.Printf("⚙️ RenderError called with status: %d", statusCode)
|
||||
|
||||
context := TemplateContext(w, r, models.TemplateData{})
|
||||
|
||||
pagePath := fmt.Sprintf("templates/error/%d.html", statusCode)
|
||||
log.Printf("📄 Checking for template file: %s", pagePath)
|
||||
|
||||
if _, err := os.Stat(pagePath); err != nil {
|
||||
log.Printf("🚫 Template file missing: %s", err)
|
||||
http.Error(w, http.StatusText(statusCode), statusCode)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("✅ Template file found, loading...")
|
||||
|
||||
tmpl := LoadTemplateFiles(fmt.Sprintf("%d.html", statusCode), pagePath)
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
err := tmpl.ExecuteTemplate(w, "layout", context)
|
||||
if err != nil {
|
||||
log.Printf("❌ Failed to render error page layout: %v", err)
|
||||
http.Error(w, http.StatusText(statusCode), statusCode)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("✅ Successfully rendered error page") // ToDo: log these to database
|
||||
}
|
||||
26
internal/helpers/template/pagination.go
Normal file
26
internal/helpers/template/pagination.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
func GetTotalPages(db *sql.DB, tableName, whereClause string, args []interface{}, pageSize int) (totalPages, totalCount int) {
|
||||
query := "SELECT COUNT(*) FROM " + tableName + " " + whereClause
|
||||
row := db.QueryRow(query, args...)
|
||||
if err := row.Scan(&totalCount); err != nil {
|
||||
return 1, 0
|
||||
}
|
||||
totalPages = (totalCount + pageSize - 1) / pageSize
|
||||
if totalPages < 1 {
|
||||
totalPages = 1
|
||||
}
|
||||
return totalPages, totalCount
|
||||
}
|
||||
|
||||
func MakePageRange(current, total int) []int {
|
||||
var pages []int
|
||||
for i := 1; i <= total; i++ {
|
||||
pages = append(pages, i)
|
||||
}
|
||||
return pages
|
||||
}
|
||||
Reference in New Issue
Block a user