-
Notifications
You must be signed in to change notification settings - Fork 1
/
gctx.go
135 lines (116 loc) · 2.51 KB
/
gctx.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
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 ctx
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/labstack/echo"
)
type grespCall struct {
ver string
c echo.Context
httpStatus []int
}
func (c CustomCtx) GResp(httpStatus ...int) *grespCall {
rs := &grespCall{
ver: apiVersion,
c: echo.Context(c),
httpStatus: httpStatus,
}
return rs
}
type gdataCall struct {
c echo.Context
httpStatus int
responseParams SuccessResp
}
func (r *grespCall) Ver(ver string) *grespCall {
r.ver = ver
return r
}
func (r *grespCall) Data(data ...interface{}) *gdataCall {
var d interface{}
if len(data) == 0 {
d = []string{}
} else {
d = data[0]
}
rs := &gdataCall{
c: r.c,
httpStatus: r.httpStatus[0],
responseParams: SuccessResp{
ApiVersion: r.ver,
Data: d,
},
}
return rs
}
// Response Json Format
// - replace string when response raw data
// - ex: replace := strings.NewReplacer("{PP_KEY}", encryptionKey)
func (r *gdataCall) Out(replace ...*strings.Replacer) (err error) {
b, err := json.Marshal(r.responseParams)
if err != nil {
return err
}
data := string(b)
for _, value := range replace {
data = value.Replace(data)
}
return r.c.JSONBlob(r.httpStatus, []byte(data))
}
// Google JSON Style error call
type GErrCall struct {
c echo.Context
HttpStatus int
ResponseParams GErrResponse
}
type GErrMessage struct {
Code uint `json:"code"`
Message string `json:"message"`
Errors []*GError `json:"errors,omitempty"`
}
type GErrResponse struct {
ApiVersion string `json:"apiVersion"`
Error GErrMessage `json:"error"`
}
func (r *grespCall) Errors(errs ...*GError) *GErrCall {
rs := &GErrCall{
c: r.c,
ResponseParams: GErrResponse{
ApiVersion: apiVersion,
Error: GErrMessage{},
},
}
if len(errs) > 0 {
if len(r.httpStatus) > 0 {
rs.HttpStatus = r.httpStatus[0]
} else {
s, _ := strconv.Atoi(fmt.Sprintf("%d", errs[0].Code)[:3])
rs.HttpStatus = s
}
rs.ResponseParams.Error.Code = errs[0].Code
rs.ResponseParams.Error.Message = errs[0].Message
rs.ResponseParams.Error.Errors = errs
}
return rs
}
// Custom HTTP Error Handler
func (r *GErrCall) Do() (err error) {
return r
}
// Response Json Out
func (r *GErrCall) Out() (err error) {
b, err := json.Marshal(r.ResponseParams)
if err != nil {
return err
}
return r.c.JSONBlob(r.HttpStatus, b)
}
func (r *GErrCall) Error() string {
b, err := json.Marshal(r.ResponseParams)
if err != nil {
return err.Error()
}
return string(b)
}