First version of web UI
This commit is contained in:
68
cmd/web/web.go
Normal file
68
cmd/web/web.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gitlab.com/kbr4/svevijesti/internal/database"
|
||||
"html/template"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var tPath = "./web/tpl/"
|
||||
var dPath = "./web/data/"
|
||||
|
||||
var templateDirs = []string{"./web/tpl", "./web/data"}
|
||||
var templates *template.Template
|
||||
|
||||
func getTemplates() (templates *template.Template, err error) {
|
||||
var allFiles []string
|
||||
for _, dir := range templateDirs {
|
||||
files2, _ := ioutil.ReadDir(dir)
|
||||
for _, file := range files2 {
|
||||
filename := file.Name()
|
||||
if strings.HasSuffix(filename, ".html") {
|
||||
filePath := filepath.Join(dir, filename)
|
||||
fmt.Println("Template found: ", filePath)
|
||||
allFiles = append(allFiles, filePath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
templates, err = template.New("").ParseFiles(allFiles...)
|
||||
return
|
||||
}
|
||||
|
||||
func init() {
|
||||
templates, _ = getTemplates()
|
||||
}
|
||||
|
||||
func rootHandler(wr http.ResponseWriter, req *http.Request) {
|
||||
title := "Pocetna"
|
||||
store, err := database.Connect()
|
||||
if err != nil {
|
||||
http.Error(wr, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
articles, err := database.ArticlesForDay(store, time.Now())
|
||||
if err != nil {
|
||||
http.Error(wr, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
data := map[string]interface{}{
|
||||
"title": title,
|
||||
"articles": articles,
|
||||
}
|
||||
|
||||
err = templates.ExecuteTemplate(wr, "homeHTML", data)
|
||||
if err != nil {
|
||||
http.Error(wr, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
http.HandleFunc("/", rootHandler)
|
||||
http.ListenAndServe(":8080", nil)
|
||||
}
|
||||
Reference in New Issue
Block a user