forked from tonyhb/tonyhb.com
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
55 lines (45 loc) · 1002 Bytes
/
api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
)
// Lists all posts in JSON for backbone
func apiList(w http.ResponseWriter, r *http.Request) {
if !acceptOk(r) {
w.WriteHeader(406)
return
}
// noindex http header for le search
w.Header().Add("robots", "noindex")
json, err := json.Marshal(posts.order())
if err != nil {
fmt.Fprint(w, err.Error())
}
// Print out our list of posts in JSON
fmt.Fprint(w, string(json))
}
func apiPost(w http.ResponseWriter, r *http.Request) {
if !acceptOk(r) {
w.WriteHeader(406)
return
}
// noindex http header for le search
w.Header().Add("robots", "noindex")
// Find our post
slug := r.URL.Path[7:]
json, _ := json.Marshal(posts.List[slug])
fmt.Fprint(w, string(json))
}
func acceptOk(r *http.Request) bool {
// If this doesn't accept JSON, throw a not acceptable.
ok := false
for _, e := range r.Header["Accept"] {
if strings.Index(e, "application/json") >= 0 {
ok = true
break
}
}
return ok
}