site/backend/christine.website/main.go

125 lines
2.4 KiB
Go
Raw Normal View History

2016-12-14 14:20:25 +00:00
package main
import (
"bytes"
2016-12-14 14:20:25 +00:00
"encoding/json"
"io/ioutil"
2016-12-14 14:20:25 +00:00
"log"
"net/http"
"os"
"path/filepath"
2016-12-14 16:56:15 +00:00
"sort"
2016-12-14 14:20:25 +00:00
"strings"
2016-12-14 16:56:15 +00:00
"time"
2016-12-14 14:20:25 +00:00
"github.com/gernest/front"
)
2016-12-14 17:30:48 +00:00
// Post is a single post summary for the menu.
2016-12-14 14:20:25 +00:00
type Post struct {
Title string `json:"title"`
Link string `json:"link"`
Summary string `json:"summary,omitifempty"`
Body string `json:"body, omitifempty"`
2016-12-14 14:20:25 +00:00
Date string `json:"date"`
}
2016-12-14 17:30:48 +00:00
// Posts implements sort.Interface for a slice of Post objects.
2016-12-14 16:56:15 +00:00
type Posts []*Post
func (p Posts) Len() int { return len(p) }
func (p Posts) Less(i, j int) bool {
iDate, _ := time.Parse("2006-01-02", p[i].Date)
jDate, _ := time.Parse("2006-01-02", p[j].Date)
return iDate.Unix() < jDate.Unix()
}
func (p Posts) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
var posts Posts
2016-12-14 14:20:25 +00:00
func init() {
err := filepath.Walk("./blog/", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
fin, err := os.Open(path)
if err != nil {
return err
}
defer fin.Close()
content, err := ioutil.ReadAll(fin)
if err != nil {
// handle error
}
2016-12-14 14:20:25 +00:00
m := front.NewMatter()
m.Handle("---", front.YAMLHandler)
front, _, err := m.Parse(bytes.NewReader(content))
2016-12-14 14:20:25 +00:00
if err != nil {
return err
}
sp := strings.Split(string(content), "\n")
sp = sp[4:]
data := strings.Join(sp, "\n")
2016-12-14 14:20:25 +00:00
p := &Post{
Title: front["title"].(string),
Date: front["date"].(string),
Link: strings.Split(path, ".")[0],
Body: data,
2016-12-14 14:20:25 +00:00
}
posts = append(posts, p)
return nil
})
if err != nil {
panic(err)
}
2016-12-14 16:56:15 +00:00
2016-12-14 17:15:16 +00:00
sort.Sort(sort.Reverse(posts))
2016-12-14 14:20:25 +00:00
}
func main() {
http.HandleFunc("/api/blog/posts", writeBlogPosts)
http.HandleFunc("/api/blog/post", func(w http.ResponseWriter, r *http.Request) {
2016-12-14 14:20:25 +00:00
q := r.URL.Query()
name := q.Get("name")
if name == "" {
goto fail
2016-12-14 14:20:25 +00:00
}
for _, p := range posts {
if strings.HasSuffix(p.Link, name) {
json.NewEncoder(w).Encode(p)
return
}
2016-12-14 14:20:25 +00:00
}
fail:
http.Error(w, "Not Found", http.StatusNotFound)
2016-12-14 14:20:25 +00:00
})
http.Handle("/dist/", http.FileServer(http.Dir("./frontend/static/")))
http.HandleFunc("/", writeIndexHTML)
log.Fatal(http.ListenAndServe(":9090", nil))
}
func writeBlogPosts(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(posts)
}
func writeIndexHTML(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./frontend/static/dist/index.html")
}