takunomi-blog/postUtils.go
2021-11-30 20:23:35 +01:00

108 lines
2.1 KiB
Go

package main
import (
"fmt"
"golang.org/x/net/html"
"html/template"
"io/ioutil"
"os"
"strings"
"time"
)
//Post : Is exported
type Post struct {
Date time.Time
NormalDate string
Title string
URLTitle string
Content template.HTML
}
const htmlDateLayout = "2006-01-02"
const normalDateLayout = "02 Jan 2006"
var modTime time.Time
func newPost(path string, f os.FileInfo, err error) error {
content, err := ioutil.ReadFile(path)
if err != nil {
fmt.Println(err)
return nil
}
title := strings.Replace(path, "posts/", "", -1)
if !strings.Contains(title, ".html") {
return nil
}
title = strings.Replace(title, ".html", "", -1)
s := string(content)
doc, _ := html.Parse(strings.NewReader(s))
dateParsed := getDate(doc)
dateFormatted := dateParsed.Format(normalDateLayout)
var p = Post{
dateParsed,
dateFormatted,
title,
strings.Replace(title, " ", "-", -1),
template.HTML(string(content[:len(content)])),
}
posts = insertPostAccordingToDate(p, posts)
return nil
}
func getDate(n *html.Node) time.Time {
var zero, d, t time.Time
if n.Type == html.ElementNode && n.Data == "time" {
for _, a := range n.Attr {
if a.Key == "datetime" {
t, _ = time.Parse(htmlDateLayout, a.Val)
return t
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
d = getDate(c)
if d != zero {
return d
}
}
return t
}
func reversePosts() []Post {
length := len(posts)
s := make([]Post, length)
for i := 0; i < length; i++ {
s[i] = posts[length-(i+1)]
}
return s
}
func getPostByURLTitle(title string) Post {
for _, post := range posts {
if post.URLTitle == title {
return post
}
}
return Post{}
}
func insertPostAccordingToDate(post Post, arr []Post) []Post {
for i, p := range arr {
if p.Date.After(post.Date) {
s := make([]Post, len(arr)+1, cap(arr)+1)
copy(s[:], arr[:]) //make a copy of the slice
copy(s[i+1:], arr[i:]) //move the upper part of the slice ahead, creating a hole
s[i] = post //insert new element into hole
return s
}
}
posts = append(posts, post)
return posts
}