-
Notifications
You must be signed in to change notification settings - Fork 37
/
api.go
73 lines (61 loc) · 1.89 KB
/
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package handler
import (
"encoding/json"
"strings"
"github.com/dinever/golf"
"github.com/dingoblog/dingo/app/utils"
)
type APISerializeable interface {
Serialize() []byte
}
type APIStatusJSON struct {
Status string `json:"status"`
Message string `json:"message"`
}
type APIResponseBodyJSON struct {
Data interface{} `json:"data"`
Status APIStatusJSON `json:"status"`
}
func NewErrorStatusJSON(msgs ...string) APIStatusJSON {
msg := strings.Join(msgs, " ")
return APIStatusJSON{Status: "error", Message: msg}
}
func NewSuccessStatusJSON(msgs ...string) APIStatusJSON {
msg := strings.Join(msgs, " ")
return APIStatusJSON{Status: "success", Message: msg}
}
func NewAPISuccessResponse(data interface{}, msgs ...string) APIResponseBodyJSON {
status := NewSuccessStatusJSON(msgs...)
return APIResponseBodyJSON{Data: data, Status: status}
}
// APIDocumentationHandler shows which routes match with what functionality,
// similar to https://api.github.com
func APIDocumentationHandler(routes map[string]map[string]interface{}) golf.HandlerFunc {
return func(ctx *golf.Context) {
routes["GET"]["api_documentation_url"] = "/api"
ctx.JSONIndent(map[string]interface{}{"request_method": routes}, "", " ")
}
}
// handleErr sends the staus code and error message formatted as JSON.
func handleErr(ctx *golf.Context, statusCode int, err error) {
ctx.JSONIndent(map[string]interface{}{
"statusCode": statusCode,
"error": err.Error(),
}, "", " ")
}
func (status APIStatusJSON) Serialize() []byte {
serializedStatus, err := json.Marshal(status)
if err != nil {
utils.LogOnError(err, "Unable to serialize status.", true)
return []byte("")
}
return serializedStatus
}
func (body APIResponseBodyJSON) Serialize() []byte {
serializedBody, err := json.Marshal(body)
if err != nil {
utils.LogOnError(err, "Unable to serialize response body.", true)
return []byte("")
}
return serializedBody
}