-
Notifications
You must be signed in to change notification settings - Fork 499
/
writer.go
56 lines (43 loc) · 1.09 KB
/
writer.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
package api
import (
"net/http"
http2 "build-booster/common/http"
"github.com/emicklei/go-restful"
)
// ErrorCode describe the error from http handler
type ErrorCode interface {
// get error string
String() string
// get error code int
Int() int
}
// RestResponse contains all response information need by a http handler
type RestResponse struct {
Resp *restful.Response
HTTPCode int
Data interface{}
ErrCode ErrorCode
Message string
Extra map[string]interface{}
WrapFunc func([]byte) []byte
}
// ReturnRest do the return work according to a RestResponse
func ReturnRest(resp *RestResponse) {
if resp.HTTPCode == 0 {
resp.HTTPCode = http.StatusOK
}
if resp.ErrCode == nil {
resp.ErrCode = ServerErrOK
}
if resp.Message == "" {
resp.Message = resp.ErrCode.String()
} else {
resp.Message = resp.ErrCode.String() + " | " + resp.Message
}
result, _ := http2.GetResponseEx(resp.ErrCode.Int(), resp.Message, resp.Data, resp.Extra)
if resp.WrapFunc != nil {
result = resp.WrapFunc(result)
}
resp.Resp.WriteHeader(resp.HTTPCode)
_, _ = resp.Resp.Write(result)
}