-
Notifications
You must be signed in to change notification settings - Fork 1
/
gctx.go
121 lines (104 loc) · 2.29 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
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) Do(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 gerrorCall struct {
c echo.Context
httpStatus int
responseParams GErrorResponse
}
type gerrorMessage struct {
Code uint `json:"code"`
Message string `json:"message"`
Errors []GError `json:"errors,omitempty"`
}
type GErrorResponse struct {
ApiVersion string `json:"apiVersion"`
Error gerrorMessage `json:"error"`
}
func (r *grespCall) Errors(errs ...GError) *gerrorCall {
rs := &gerrorCall{
c: r.c,
responseParams: GErrorResponse{
ApiVersion: apiVersion,
Error: gerrorMessage{},
},
}
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
}
func (r *gerrorCall) Do() (err error) {
b, err := json.Marshal(r.responseParams)
if err != nil {
return err
}
return r.c.JSONBlob(r.httpStatus, b)
}