refactored blog

This commit is contained in:
Jacob 2021-11-30 20:23:35 +01:00
parent ea6b16d6ab
commit 29745008c0
2 changed files with 28 additions and 92 deletions

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"html/template" "html/template"
"net/http" "net/http"
"path/filepath"
"os" "os"
"strings" "strings"
) )
@ -22,19 +23,8 @@ var templates = template.Must(template.ParseFiles("templates/blog.tmpl", "templa
func main() { func main() {
NewPostsCollection() buildHandlers()
retrievePosts()
http.HandleFunc("/about/", aboutHandler)
http.HandleFunc("/past/", pastHandler)
http.HandleFunc("/contact/", contactHandler)
http.HandleFunc("/post/", postHandler)
http.HandleFunc("/", pastHandler)
//http.HandleFunc("/", blogHandler)
http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("images"))))
http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
//posts = PostsCollection[:]
setPostsCollection()
if os.Args[1] == "local" { if os.Args[1] == "local" {
http.ListenAndServe(":8080", nil) http.ListenAndServe(":8080", nil)
@ -46,8 +36,21 @@ func main() {
} }
func setPostsCollection() { func retrievePosts() {
posts = PostsCollection[:] posts = nil
filepath.Walk("./posts", newPost)
posts = reversePosts()
}
func buildHandlers() {
http.HandleFunc("/about/", aboutHandler)
http.HandleFunc("/past/", pastHandler)
http.HandleFunc("/contact/", contactHandler)
http.HandleFunc("/post/", postHandler)
http.HandleFunc("/update", updateHandler)
http.HandleFunc("/", pastHandler)
http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("images"))))
http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
} }
func errorHandler(w http.ResponseWriter, req *http.Request, status int) { func errorHandler(w http.ResponseWriter, req *http.Request, status int) {
@ -57,20 +60,6 @@ func errorHandler(w http.ResponseWriter, req *http.Request, status int) {
} }
} }
func blogHandler(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/" {
errorHandler(w, req, http.StatusNotFound)
return
}
length := len(posts)
posts = posts[:3]
//posts = getNewestPosts(3)
page := Page{name, posts, "past"}
//page := Page{name, posts, "blog"}
renderTemplates(w, page)
posts = posts[:length]
}
func postHandler(w http.ResponseWriter, r *http.Request) { func postHandler(w http.ResponseWriter, r *http.Request) {
title := strings.TrimPrefix(r.URL.Path, "/post/") title := strings.TrimPrefix(r.URL.Path, "/post/")
posts := []Post{getPostByURLTitle(title)} posts := []Post{getPostByURLTitle(title)}
@ -93,6 +82,10 @@ func contactHandler(w http.ResponseWriter, r *http.Request) {
renderTemplates(w, page) renderTemplates(w, page)
} }
func updateHandler(w http.ResponseWriter, r *http.Request) {
retrievePosts()
}
func renderTemplates(w http.ResponseWriter, p Page) { func renderTemplates(w http.ResponseWriter, p Page) {
s1 := templates.Lookup("blog.tmpl") s1 := templates.Lookup("blog.tmpl")
err := s1.ExecuteTemplate(w, "blog", p) err := s1.ExecuteTemplate(w, "blog", p)

View File

@ -6,7 +6,6 @@ import (
"html/template" "html/template"
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath"
"strings" "strings"
"time" "time"
) )
@ -22,54 +21,7 @@ type Post struct {
const htmlDateLayout = "2006-01-02" const htmlDateLayout = "2006-01-02"
const normalDateLayout = "02 Jan 2006" const normalDateLayout = "02 Jan 2006"
var modTime time.Time var modTime time.Time
var PostsCollection []Post
func NewPostsCollection() {
verifyFolderModification()
initializeCollection()
go acquirePosts(100)
}
func initializeCollection() {
PostsCollection = nil
filepath.Walk("./posts", newPost)
PostsCollection = reversePosts()
}
func acquirePosts(duration time.Duration) {
for {
if verifyFolderModification() == true {
initializeCollection()
setPostsCollection()
}
time.Sleep(duration * time.Second)
}
}
func verifyFolderModification() bool {
f, err := os.Open("./posts")
if err != nil {
fmt.Println("file-error here: \n", f)
f.Close()
return false
}
info, err := f.Stat()
if err != nil {
fmt.Println("info here: \n", info)
f.Close()
return false
}
_modTime := info.ModTime()
if modTime != _modTime {
modTime = _modTime
f.Close()
return true
}
f.Close()
return false
}
func newPost(path string, f os.FileInfo, err error) error { func newPost(path string, f os.FileInfo, err error) error {
content, err := ioutil.ReadFile(path) content, err := ioutil.ReadFile(path)
@ -95,7 +47,7 @@ func newPost(path string, f os.FileInfo, err error) error {
template.HTML(string(content[:len(content)])), template.HTML(string(content[:len(content)])),
} }
PostsCollection = insertPostAccordingToDate(p, PostsCollection) posts = insertPostAccordingToDate(p, posts)
return nil return nil
} }
@ -123,25 +75,16 @@ func getDate(n *html.Node) time.Time {
} }
func reversePosts() []Post { func reversePosts() []Post {
length := len(PostsCollection) length := len(posts)
s := make([]Post, length) s := make([]Post, length)
for i := 0; i < length; i++ { for i := 0; i < length; i++ {
s[i] = PostsCollection[length-(i+1)] s[i] = posts[length-(i+1)]
} }
return s return s
} }
func getNewestPosts(numberOfPosts int) []Post {
var posts []Post
l := len(PostsCollection)
for i := l - 1; i >= l-numberOfPosts; i-- {
posts = append(posts, PostsCollection[i])
}
return posts
}
func getPostByURLTitle(title string) Post { func getPostByURLTitle(title string) Post {
for _, post := range PostsCollection { for _, post := range posts {
if post.URLTitle == title { if post.URLTitle == title {
return post return post
} }
@ -159,6 +102,6 @@ func insertPostAccordingToDate(post Post, arr []Post) []Post {
return s return s
} }
} }
PostsCollection = append(PostsCollection, post) posts = append(posts, post)
return PostsCollection return posts
} }