takunomi-blog/main.go

123 lines
2.8 KiB
Go

package main
import (
"fmt"
"html/template"
"net/http"
"path/filepath"
"os"
"strings"
)
type Page struct {
Title string
Years [][]Post
//Years map[int][]Post
Posts []Post
CurrentPage string
}
var style = ``
var name = "takunomi"
var posts []Post
var years [][]Post
//var years map[int][]Post
var templates = template.Must(template.ParseFiles(
"templates/blog.tmpl",
"templates/about.tmpl",
"templates/keru_shoujo.tmpl",
"templates/past.tmpl",
"templates/contact.tmpl",
"templates/blog_roll.tmpl",
"templates/title.tmpl",
"templates/navbar.tmpl",
"templates/main.tmpl",
"templates/post.tmpl"))
func main() {
buildHandlers()
retrievePosts()
if os.Args[1] == "local" {
http.ListenAndServe(":8080", nil)
}
if os.Args[1] == "ext" {
http.ListenAndServe(":35291", nil)
}
}
func retrievePosts() {
posts = nil
years = nil
//years = make(map[int][]Post)
filepath.Walk("./posts", newPost)
years = reverseYears()
for i := 0; i<len(years); i++ {
years[i] = reversePosts(years[i])
}
//posts = reversePosts()
}
func buildHandlers() {
http.HandleFunc("/about/", aboutHandler)
http.HandleFunc("/past/", pastHandler)
http.HandleFunc("/the_girl_who_kicked_a_rabbit/", keruHandler)
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) {
w.WriteHeader(status)
if status == http.StatusNotFound {
fmt.Fprint(w, "custom 404")
}
}
func postHandler(w http.ResponseWriter, r *http.Request) {
title := strings.TrimPrefix(r.URL.Path, "/post/")
posts := []Post{getPostByURLTitle(title)}
page := Page{name, years, posts, "blog"}
renderTemplates(w, page)
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
page := Page{name, nil, []Post{}, "about"}
renderTemplates(w, page)
}
func pastHandler(w http.ResponseWriter, r *http.Request) {
page := Page{name, years, posts, "past"}
renderTemplates(w, page)
}
func keruHandler(w http.ResponseWriter, r *http.Request) {
posts := []Post{getPostByURLTitle("The-Girl-Who-Kicked-a-Rabbit")}
page := Page{name, years, posts, "blog"}
renderTemplates(w, page)
}
func contactHandler(w http.ResponseWriter, r *http.Request) {
page := Page{name, nil, []Post{}, "contact"}
renderTemplates(w, page)
}
func updateHandler(w http.ResponseWriter, r *http.Request) {
retrievePosts()
}
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)
}
}