-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
82 lines (68 loc) · 1.52 KB
/
response.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
package helpers
import (
"encoding/json"
"github.com/kataras/iris"
)
type Detail struct {
Error interface{} `json:"errors,omitempty"`
Data interface{} `json:"data,omitempty"`
}
// Response struct for message json
type Messages struct {
Status int `json:"status"`
Success bool `json:"success"`
*Detail
}
// Validation HTTP Status Code
// Retrun true or false
func IsSuccessCode(c int) bool {
return c > 199 && c < 300
}
// Check JSON type
func IsJSON(s string) bool {
var js map[string]interface{}
return json.Unmarshal([]byte(s), &js) == nil
}
// Simple json response
// Handler from kataras/ iris
// code of HTTP status code
// Message Body
func NewResponse(ctx iris.Context, code int, content interface{}) {
// check status code success
status := IsSuccessCode(code)
// Set value to struct
var res Messages
res.Status = code
res.Success = status
// Init body response
body := make(map[string]interface{})
var returns interface{}
returns = nil
if _, ok := content.(string); ok {
// check if content as JSON
if IsJSON(content.(string)) == false {
body["message"] = content
} else {
json.Unmarshal([]byte(content.(string)), &body)
}
} else {
returns = content
}
// TO DO
// WILL REFACTOR THIS LINE CODE
if status == true {
if returns != nil {
res.Detail = &Detail{Data: returns}
} else {
res.Detail = &Detail{Data: body}
}
} else {
if returns != nil {
res.Detail = &Detail{Error: returns}
} else {
res.Detail = &Detail{Error: body}
}
}
ctx.StatusCode(code)
ctx.JSON(res)
}