package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/CalebQ42/darkstorm-server/internal/backend"
"github.com/CalebQ42/darkstorm-server/internal/blog"
)
const (
blogTitle = "
"
blogAuthor = "By %v
"
blogCreate = "Written on: %v
"
blogMain = "%v
"
authorInfo = `
About the author:
 |
%v%v |
`
)
func latestBlogsHandle(w http.ResponseWriter, r *http.Request) {
latest, err := blogApp.LatestBlogs(0)
if err != nil {
if err == backend.ErrNotFound {
w.WriteHeader(404)
sendContent(w, r, "Page not found", "", "")
return
}
w.WriteHeader(http.StatusInternalServerError)
log.Println("error getting latest blogs:", err)
sendContent(w, r, "Error getting page", "", "")
return
}
var out string
for _, b := range latest {
out += blogElement(b)
}
sendContent(w, r, out, "", "")
}
func blogHandle(w http.ResponseWriter, r *http.Request, blog string) {
bl, err := blogApp.Blog(blog)
if err != nil {
if err == backend.ErrNotFound {
w.WriteHeader(404)
sendContent(w, r, "Page not found", "", "")
return
}
w.WriteHeader(http.StatusInternalServerError)
log.Printf("error getting blog %v: %v\n", blog, err)
sendContent(w, r, "Error getting page", "", "")
return
}
sendContent(w, r, blogElement(bl), bl.Title, bl.Favicon)
}
func blogElement(b *blog.Blog) (out string) {
out = fmt.Sprintf(blogTitle, b.ID, b.ID, b.Title)
auth, err := blogApp.GetAuthor(b)
if err == nil {
out += fmt.Sprintf(blogAuthor, auth.Name)
} else {
out += fmt.Sprintf(blogAuthor, "unknown")
}
cTime := time.Unix(b.CreateTime, 0).Format(time.DateOnly)
if b.UpdateTime > b.CreateTime {
out += fmt.Sprintf(blogCreate, cTime+"; Last updated on: "+time.Unix(b.UpdateTime, 0).Format(time.DateOnly))
} else {
out += fmt.Sprintf(blogCreate, cTime)
}
out += fmt.Sprintf(blogMain, b.Blog)
if err == nil {
out += authorSection(auth)
}
return
}
func authorSection(a *blog.Author) string {
return fmt.Sprintf(authorInfo, a.PicURL, a.Name+"'s profile picture", a.Name, a.About)
}