Skip to content

Instantly share code, notes, and snippets.

@will3942
Created December 4, 2013 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save will3942/7795299 to your computer and use it in GitHub Desktop.
Save will3942/7795299 to your computer and use it in GitHub Desktop.
Go: displaying blog posts on the home page.
package main
import (
"html/template"
"net/http"
"path/filepath"
"strings"
"io/ioutil"
"github.com/russross/blackfriday"
)
type Post struct {
Title string
Date string
Summary string
Body string
File string
}
func handlerequest(w http.ResponseWriter, r *http.Request) {
posts := getPosts()
t := template.New("index.html")
t, _ = t.ParseFiles("index.html")
t.Execute(w, posts)
}
func getPosts() []Post{
a := []Post{}
files, _ := filepath.Glob("posts/*")
for _, f := range files {
file := strings.Replace(f, "posts/", "", -1)
file = strings.Replace(file, ".md", "", -1)
fileread, _ := ioutil.ReadFile(f)
lines := strings.Split(string(fileread), "\n")
title := string(lines[0])
date := string(lines[1])
summary := string(lines[2])
body := strings.Join(lines[3:len(lines)], "\n")
body = string(blackfriday.MarkdownCommon([]byte(body)))
a = append(a, Post{title, date, summary, body, file})
}
return a
}
func main() {
http.HandleFunc("/", handlerequest)
http.ListenAndServe(":8000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment