func blogHandler(w http.ResponseWriter, r *http.Request) { log.Printf("%s - %s\n", r.RemoteAddr, r.URL.Path) // Get all the posts out of the directory files, _ := ioutil.ReadDir("./content/posts") posts := make(map[blog.MetaData][]string) var meta_data []blog.MetaData for _, f := range files { markup, meta, err := blog.ParseHTMLFromFile("./content/posts/" + f.Name()) if err != nil { log.Printf("Error from ParseHTMLFromFile(): %+v", err) } posts[meta] = markup meta_data = append(meta_data, meta) } // Print them to a buffer, inserting HTML appropriately sort.Sort(ByTimestamp(meta_data)) var buf bytes.Buffer buf.WriteString("{{define \"blog_content\"}}") for k, v := range meta_data { // Write the post to the buffer, insert the timestamp after header buf.WriteString("<article>") markup := posts[v] for i := 0; i < len(markup); i++ { buf.WriteString(markup[i]) } buf.WriteString("</article>") // Insert a divider between posts if k != len(meta_data)-1 { buf.WriteString("<hr />") } } buf.WriteString("{{end}}") templates.Parse(buf.String()) if r.Method != "GET" { return } if len(r.URL.RawQuery) == 0 { err := renderTemplate(w, r, "blog") if err != nil { log.Println(err.Error()) } return } err := renderTemplate(w, r, "blog") if err != nil { log.Println(err.Error()) http.Error(w, http.StatusText(500), 500) return } }
func singleBlogHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) name := vars["name"] log.Printf("%s - %s\n", r.RemoteAddr, r.URL.Path) // Get the file with md at the end markup, _, err := blog.ParseHTMLFromFile("./content/posts/" + name + ".md") var buf bytes.Buffer buf.WriteString("{{define \"blog_content\"}}") // Write the post to the buffer, insert the timestamp after header buf.WriteString("<article>") for i := 0; i < len(markup); i++ { buf.WriteString(markup[i]) } buf.WriteString("</article>") buf.WriteString("{{end}}") templates.Parse(buf.String()) if r.Method != "GET" { return } if len(r.URL.RawQuery) == 0 { err := renderTemplate(w, r, "blog") if err != nil { log.Println(err.Error()) } return } err = renderTemplate(w, r, "blog") if err != nil { log.Println(err.Error()) http.Error(w, http.StatusText(500), 500) return } }