takunomi-blog/websiteTemplate.go

103 lines
2.4 KiB
Go

package main
import (
"fmt"
"html/template"
"net/http"
"os"
"strings"
)
//Page : Is exported to PostCollection
type Page struct {
Title string
Posts []Post
CurrentPage string
}
var style = ``
var name = "takunomi"
var posts []Post
var templates = template.Must(template.ParseFiles("templates/blog.tmpl", "templates/about.tmpl", "templates/past.tmpl", "templates/contact.tmpl", "templates/blog_roll.tmpl", "templates/post.tmpl"))
func main() {
NewPostsCollection()
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" {
http.ListenAndServe(":8080", nil)
}
if os.Args[1] == "ext" {
http.ListenAndServe(":35291", nil)
}
}
func setPostsCollection() {
posts = PostsCollection[:]
}
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
}
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) {
title := strings.TrimPrefix(r.URL.Path, "/post/")
posts := []Post{getPostByURLTitle(title)}
page := Page{name, posts, "blog"}
renderTemplates(w, page)
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
page := Page{name, []Post{}, "about"}
renderTemplates(w, page)
}
func pastHandler(w http.ResponseWriter, r *http.Request) {
page := Page{name, posts, "past"}
renderTemplates(w, page)
}
func contactHandler(w http.ResponseWriter, r *http.Request) {
page := Page{name, []Post{}, "contact"}
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)
}
}