Files
old-svevijesti/internal/server/articles.go
2022-02-15 05:43:52 +01:00

64 lines
1.4 KiB
Go

package server
import (
"github.com/gorilla/mux"
"gitlab.com/kbr4/svevijesti/internal/database"
"net/http"
"strconv"
"time"
)
func rootHandler(wr http.ResponseWriter, req *http.Request) {
title := "Pocetna"
store, err := database.Connect()
if err != nil {
http.Error(wr, err.Error(), http.StatusInternalServerError)
}
defer store.Close()
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 articleHandler(wr http.ResponseWriter, req *http.Request) {
store, err := database.Connect()
if err != nil {
http.Error(wr, err.Error(), http.StatusInternalServerError)
}
defer store.Close()
vars := mux.Vars(req)
articleID, err := strconv.Atoi(vars["id"])
if err != nil {
articleID = -1
}
articleSlug := vars["slug"]
article, err := database.ArticleByID(store, articleID, articleSlug)
if err != nil {
http.Error(wr, err.Error(), http.StatusNotFound)
}
title := article.Title
data := map[string]interface{}{
"title": title,
"article": article,
}
err = templates.ExecuteTemplate(wr, "articleHTML", data)
if err != nil {
http.Error(wr, err.Error(), http.StatusInternalServerError)
}
}