forked from ohayo-jacob/takunomi-blog
93 lines
2.0 KiB
Go
93 lines
2.0 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("blog.tmpl", "about.tmpl", "past.tmpl", "contact.tmpl", "blog_roll.tmpl", "style.tmpl", "post.tmpl"))
|
|
|
|
func main() {
|
|
|
|
NewPostsCollection()
|
|
|
|
http.HandleFunc("/about/", aboutHandler)
|
|
http.HandleFunc("/past/", pastHandler)
|
|
http.HandleFunc("/contact/", contactHandler)
|
|
http.HandleFunc("/post/", postHandler)
|
|
http.HandleFunc("/", blogHandler)
|
|
posts = PostsCollection[:]
|
|
|
|
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
|
|
}
|
|
length := len(posts)
|
|
posts = posts[:3]
|
|
//posts = getNewestPosts(3)
|
|
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)
|
|
}
|
|
}
|