takunomi-blog/websiteTemplate.go

71 lines
1.5 KiB
Go
Raw Normal View History

2017-11-07 11:16:35 +00:00
package main
import (
"html/template"
"net/http"
"strings"
2017-11-07 11:47:37 +00:00
"os"
2017-11-07 11:16:35 +00:00
)
type Page struct {
Title string
MenuItems []string
Posts []Post
}
var name string = "takunomi"
var posts []Post
var sections = []string {"about","past", "contact"}
var templates = template.Must(template.ParseFiles("blog.tmpl", "blog_roll.tmpl", "style.tmpl", "post.tmpl"))
func main() {
2017-11-07 11:47:37 +00:00
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)
}
//http.ListenAndServe(":8080", 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-07 11:16:35 +00:00
posts = getNewestPosts(3)
page := Page {name, sections, posts}
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}
renderTemplates(w, page)
}
func renderTemplates (w http.ResponseWriter, p Page) {
s1 := templates.Lookup("blog.tmpl")
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)
}