-
Notifications
You must be signed in to change notification settings - Fork 0
/
JsonResponse.go
53 lines (40 loc) · 1.02 KB
/
JsonResponse.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
package goboot
import (
"github.com/gofiber/fiber/v2"
"github.com/lamgor666/goboot-common/util/jsonx"
"strings"
)
type JsonResponse struct {
payload interface{}
}
func NewJsonResponse(payload interface{}) JsonResponse {
return JsonResponse{payload: payload}
}
func (p JsonResponse) GetContentType() string {
return fiber.MIMEApplicationJSONCharsetUTF8
}
func (p JsonResponse) GetContents() (statusCode int, contents string) {
statusCode = 200
if s1, ok := p.payload.(string); ok {
s1 = strings.TrimSpace(s1)
if p.isJson(s1) {
contents = s1
return
}
}
opts := jsonx.NewToJsonOption().HandleTimeField().StripZeroTimePart()
contents = strings.TrimSpace(jsonx.ToJson(p.payload, opts))
if !p.isJson(contents) {
contents = "{}"
}
return
}
func (p JsonResponse) isJson(contents string) bool {
var flag bool
if strings.HasPrefix(contents, "{") && strings.HasSuffix(contents, "}") {
flag = true
} else if strings.HasPrefix(contents, "[") && strings.HasSuffix(contents, "]") {
flag = true
}
return flag
}