backend: return individual posts as json

This commit is contained in:
Cadey Ratio 2016-12-14 11:53:26 -08:00
parent b65845c8ac
commit 766c6cd3d0
1 changed files with 26 additions and 16 deletions

View File

@ -1,12 +1,12 @@
package main package main
import ( import (
"bytes"
"encoding/json" "encoding/json"
"fmt" "io/ioutil"
"log" "log"
"net/http" "net/http"
"os" "os"
"path"
"path/filepath" "path/filepath"
"sort" "sort"
"strings" "strings"
@ -19,7 +19,8 @@ import (
type Post struct { type Post struct {
Title string `json:"title"` Title string `json:"title"`
Link string `json:"link"` Link string `json:"link"`
Summary string `json:"summary"` Summary string `json:"summary,omitifempty"`
Body string `json:"body, omitifempty"`
Date string `json:"date"` Date string `json:"date"`
} }
@ -53,17 +54,27 @@ func init() {
} }
defer fin.Close() defer fin.Close()
content, err := ioutil.ReadAll(fin)
if err != nil {
// handle error
}
m := front.NewMatter() m := front.NewMatter()
m.Handle("---", front.YAMLHandler) m.Handle("---", front.YAMLHandler)
front, _, err := m.Parse(fin) front, _, err := m.Parse(bytes.NewReader(content))
if err != nil { if err != nil {
return err return err
} }
sp := strings.Split(string(content), "\n")
sp = sp[4:]
data := strings.Join(sp, "\n")
p := &Post{ p := &Post{
Title: front["title"].(string), Title: front["title"].(string),
Date: front["date"].(string), Date: front["date"].(string),
Link: strings.Split(path, ".")[0], Link: strings.Split(path, ".")[0],
Body: data,
} }
posts = append(posts, p) posts = append(posts, p)
@ -80,24 +91,23 @@ func init() {
func main() { func main() {
http.HandleFunc("/api/blog/posts", writeBlogPosts) http.HandleFunc("/api/blog/posts", writeBlogPosts)
http.HandleFunc("/api/blog/name", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/api/blog/post", func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query() q := r.URL.Query()
name := q.Get("name") name := q.Get("name")
fin, err := os.Open(path.Join("./blog", name)) if name == "" {
if err != nil { goto fail
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} }
defer fin.Close()
m := front.NewMatter() for _, p := range posts {
m.Handle("---", front.YAMLHandler) if strings.HasSuffix(p.Link, name) {
_, body, err := m.Parse(fin) json.NewEncoder(w).Encode(p)
if err != nil { return
http.Error(w, err.Error(), http.StatusInternalServerError) }
} }
fmt.Fprintln(w, body)
fail:
http.Error(w, "Not Found", http.StatusNotFound)
}) })
http.Handle("/dist/", http.FileServer(http.Dir("./frontend/static/"))) http.Handle("/dist/", http.FileServer(http.Dir("./frontend/static/")))
http.HandleFunc("/", writeIndexHTML) http.HandleFunc("/", writeIndexHTML)