/
helper.go
57 lines (48 loc) · 1.15 KB
/
helper.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
package helper
import (
"net/http"
"github.com/labstack/echo"
)
// HTTPResponse model
type HTTPResponse struct {
Code int `json:"status"`
Success bool `json:"success"`
Message string `json:"message"`
Meta *Meta `json:"meta,omitempty"`
Data interface{} `json:"data,omitempty"`
Error interface{} `json:"error,omitempty"`
}
// Meta model
type Meta struct {
Page int `json:"page"`
Offset int `json:"offset"`
Limit int `json:"limit"`
Total int `json:"totalRecords"`
}
// NewHTTPResponse constructor
func NewHTTPResponse(code int, message string, params ...interface{}) *HTTPResponse {
commonResponse := new(HTTPResponse)
for i, param := range params {
if i == 0 {
commonResponse.Data = param
} else if i == 1 {
if meta, ok := param.(Meta); ok {
commonResponse.Meta = &meta
}
}
}
if code < http.StatusBadRequest {
commonResponse.Success = true
}
commonResponse.Code = code
commonResponse.Message = message
return commonResponse
}
// SetResponse method
func (h *HTTPResponse) SetResponse(c echo.Context) error {
if !h.Success {
h.Error = h.Data
h.Data = nil
}
return c.JSON(h.Code, h)
}