takunomi-blog/websiteTemplate.go

73 lines
1.5 KiB
Go
Raw Normal View History

2017-11-07 11:16:35 +00:00
package main
import (
2017-11-09 08:56:33 +00:00
"fmt"
2017-11-07 11:16:35 +00:00
"html/template"
"net/http"
2017-11-07 11:47:37 +00:00
"os"
2017-11-09 08:56:33 +00:00
"strings"
2017-11-07 11:16:35 +00:00
)
2017-11-09 08:56:33 +00:00
//Page : Is exported to PostCollection
2017-11-07 11:16:35 +00:00
type Page struct {
2017-11-09 08:56:33 +00:00
Title string
2017-11-07 11:16:35 +00:00
MenuItems []string
2017-11-09 08:56:33 +00:00
Posts []Post
2017-11-07 11:16:35 +00:00
}
2017-11-09 08:56:33 +00:00
var name = "takunomi"
2017-11-07 11:16:35 +00:00
var posts []Post
2017-11-09 08:56:33 +00:00
var sections = []string{"about", "past", "contact"}
var templates = template.Must(template.ParseFiles("blog.tmpl", "blog_roll.tmpl", "style.tmpl", "post.tmpl"))
2017-11-07 11:16:35 +00:00
func main() {
2017-11-07 11:47:37 +00:00
2017-11-17 14:12:04 +00:00
InitializeCollection()
go AcquirePosts(100)
2017-11-07 11:16:35 +00:00
http.HandleFunc("/", blogHandler)
http.HandleFunc("/post/", postHandler)
2017-11-07 11:47:37 +00:00
if os.Args[1] == "local" {
http.ListenAndServe(":8080", nil)
}
if os.Args[1] == "ext" {
http.ListenAndServe(":35291", nil)
}
2017-11-07 11:16:35 +00:00
}
2017-11-07 11:52:02 +00:00
func errorHandler(w http.ResponseWriter, req *http.Request, status int) {
w.WriteHeader(status)
if status == http.StatusNotFound {
fmt.Fprint(w, "custom 404")
}
}
2017-11-07 11:16:35 +00:00
func blogHandler(w http.ResponseWriter, req *http.Request) {
2017-11-07 11:52:02 +00:00
if req.URL.Path != "/" {
errorHandler(w, req, http.StatusNotFound)
return
}
2017-11-09 08:56:33 +00:00
posts = getNewestPosts(3)
page := Page{name, sections, posts}
2017-11-07 11:16:35 +00:00
renderTemplates(w, page)
}
2017-11-09 08:56:33 +00:00
func postHandler(w http.ResponseWriter, r *http.Request) {
title := strings.TrimPrefix(r.URL.Path, "/post/")
posts := []Post{getPostByURLTitle(title)}
page := Page{name, sections, posts}
2017-11-07 11:16:35 +00:00
renderTemplates(w, page)
}
2017-11-09 08:56:33 +00:00
func renderTemplates(w http.ResponseWriter, p Page) {
2017-11-07 11:16:35 +00:00
s1 := templates.Lookup("blog.tmpl")
2017-11-09 08:56:33 +00:00
s1.ExecuteTemplate(w, "blog", p)
s2 := templates.Lookup("blog_roll.tmpl")
s2.ExecuteTemplate(w, "blog_roll", nil)
s3 := templates.Lookup("post.tmpl")
s3.ExecuteTemplate(w, "post", nil)
2017-11-07 11:16:35 +00:00
}