summaryrefslogtreecommitdiff
path: root/system/api/server.go
blob: 5fa0bfcb1ae16d5b0388f43b2a809193a565f092 (plain)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package api

import (
	"bytes"
	"encoding/json"
	"log"
	"net/http"

	"github.com/nilslice/cms/content"
	"github.com/nilslice/cms/system/db"
)

func init() {
	http.HandleFunc("/api/types", func(res http.ResponseWriter, req *http.Request) {
		var types = []string{}
		for t := range content.Types {
			types = append(types, string(t))
		}

		j, err := toJSON(types)
		if err != nil {
			res.WriteHeader(http.StatusInternalServerError)
			return
		}

		res.Header().Set("Content-Type", "application/json")
		res.Write(j)
	})

	http.HandleFunc("/api/posts", func(res http.ResponseWriter, req *http.Request) {
		q := req.URL.Query()
		t := q.Get("type")
		// TODO: implement pagination
		// num := q.Get("num")
		// page := q.Get("page")

		if t == "" {
			res.WriteHeader(http.StatusBadRequest)
			return
		}

		posts := db.GetAll(t)
		var all = []json.RawMessage{}
		for _, post := range posts {
			all = append(all, post)
		}

		j, err := fmtJSON(all...)
		if err != nil {
			res.WriteHeader(http.StatusInternalServerError)
			return
		}

		res.Header().Set("Content-Type", "application/json")
		res.Write(j)
	})

	http.HandleFunc("/api/post", func(res http.ResponseWriter, req *http.Request) {
		q := req.URL.Query()
		id := q.Get("id")
		t := q.Get("type")

		if t == "" || id == "" {
			res.WriteHeader(http.StatusBadRequest)
			return
		}

		post, err := db.Get(t + ":" + id)
		if err != nil {
			res.WriteHeader(http.StatusInternalServerError)
			return
		}

		j, err := fmtJSON(json.RawMessage(post))
		if err != nil {
			res.WriteHeader(http.StatusInternalServerError)
			return
		}

		res.Header().Set("Content-Type", "application/json")
		res.Write(j)
	})

}

func fmtJSON(data ...json.RawMessage) ([]byte, error) {
	var msg = []json.RawMessage{}
	for _, d := range data {
		msg = append(msg, d)
	}

	resp := map[string][]json.RawMessage{
		"data": msg,
	}

	var buf = &bytes.Buffer{}
	enc := json.NewEncoder(buf)
	err := enc.Encode(resp)
	if err != nil {
		log.Println("Failed to encode data to JSON:", err)
		return nil, err
	}

	return buf.Bytes(), nil
}

func toJSON(data []string) ([]byte, error) {
	var buf = &bytes.Buffer{}
	enc := json.NewEncoder(buf)
	resp := map[string][]string{
		"data": data,
	}

	err := enc.Encode(resp)
	if err != nil {
		log.Println("Failed to encode data to JSON:", err)
		return nil, err
	}

	return buf.Bytes(), nil
}

func wrapJSON(json []byte) []byte {
	var buf = &bytes.Buffer{}
	buf.Write([]byte("{data:"))
	buf.Write(json)
	buf.Write([]byte("}"))

	return buf.Bytes()
}

// Run start the JSON API
func Run(port string) {
	log.Fatal(http.ListenAndServe(":"+port, nil))
}