-
Notifications
You must be signed in to change notification settings - Fork 10
/
response.go
76 lines (64 loc) · 1.82 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
/*
* Copyright (c) 2021 THL A29 Limited, a Tencent company. All rights reserved
*
* This source code file is licensed under the MIT License, you may obtain a copy of the License at
*
* http://opensource.org/licenses/MIT
*
*/
package http
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/TencentBlueKing/bk-turbo/src/backend/booster/common/blog"
"github.com/TencentBlueKing/bk-turbo/src/backend/booster/common/codec"
)
// APIResponse response for api request
type APIResponse struct {
Result bool `json:"result"`
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
// GetResponse adaptor
func GetResponse(code int, message string, data interface{}) ([]byte, error) {
return createResponseEx(code, message, data, nil)
}
// GetResponseEx extension adaptor
func GetResponseEx(code int, message string, data interface{}, extra map[string]interface{}) ([]byte, error) {
return createResponseEx(code, message, data, extra)
}
func createResponseEx(code int, message string, data interface{}, extra map[string]interface{}) (r []byte, err error) {
result := code == 0
if !result {
appName := filepath.Base(os.Args[0])
message = fmt.Sprintf("(%s):%s", appName, message)
}
resp := APIResponse{result, code, message, data}
t1 := time.Now()
if err = codec.EncJSON(resp, &r); err != nil {
return
}
if delta := time.Now().Sub(t1); delta > 10*time.Millisecond {
blog.Info("json cost: %s", delta)
}
return addExtraField(r, extra)
}
func addExtraField(s []byte, extra map[string]interface{}) (r []byte, err error) {
if extra == nil {
return s, nil
}
var jsn map[string]interface{}
if err = codec.DecJSON(s, &jsn); err != nil {
return
}
for k, v := range extra {
if _, ok := jsn[k]; !ok {
jsn[k] = v
}
}
err = codec.EncJSON(jsn, &r)
return
}