takunomi-blog/websiteTemplate.go

89 lines
2.1 KiB
Go

package main
import (
"fmt"
"html/template"
"net/http"
"os"
"strings"
)
//Page : Is exported to PostCollection
type Page struct {
Title string
MenuItems []template.HTML
Posts []Post
CurrentPage string
}
var style = ``
var name = "takunomi"
var posts []Post
var sections = []template.HTML{
`<a class="no-link menuElement" style="text-decoration: none; color: inherit" href=/about>about</a>`,
`<a class="no-link menuElement" style="text-decoration: none; color: inherit" href=/past>past</a>`,
`<a class="no-link menuElement" style="text-decoration: none; color: inherit" href=/contact>contact</a>`,
}
var templates = template.Must(template.ParseFiles("blog.tmpl", "about.tmpl", "past.tmpl", "blog_roll.tmpl", "style.tmpl", "post.tmpl"))
func main() {
NewPostsCollection()
http.HandleFunc("/about/", aboutHandler)
http.HandleFunc("/past/", pastHandler)
http.HandleFunc("/post/", postHandler)
http.HandleFunc("/", blogHandler)
if os.Args[1] == "local" {
http.ListenAndServe(":8080", nil)
}
if os.Args[1] == "ext" {
http.ListenAndServe(":35291", nil)
}
}
func errorHandler(w http.ResponseWriter, req *http.Request, status int) {
w.WriteHeader(status)
if status == http.StatusNotFound {
fmt.Fprint(w, "custom 404")
}
}
func blogHandler(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/" {
errorHandler(w, req, http.StatusNotFound)
return
}
posts = getNewestPosts(3)
page := Page{name, sections, posts, "blog"}
renderTemplates(w, page)
}
func postHandler(w http.ResponseWriter, r *http.Request) {
title := strings.TrimPrefix(r.URL.Path, "/post/")
posts := []Post{getPostByURLTitle(title)}
page := Page{name, sections, posts, "blog"}
renderTemplates(w, page)
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
page := Page{name, sections, []Post{}, "about"}
renderTemplates(w, page)
}
func pastHandler(w http.ResponseWriter, r *http.Request) {
page := Page{name, sections, posts, "past"}
renderTemplates(w, page)
}
func renderTemplates(w http.ResponseWriter, p Page) {
s1 := templates.Lookup("blog.tmpl")
err := s1.ExecuteTemplate(w, "blog", p)
if err != nil {
fmt.Println("error is ", err)
}
}