forked from micro-plat/hydra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
91 lines (88 loc) · 2.29 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
83
84
85
86
87
88
89
90
91
package middleware
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"strings"
"github.com/micro-plat/hydra/conf"
"github.com/micro-plat/hydra/context"
"github.com/micro-plat/hydra/servers"
"github.com/micro-plat/hydra/servers/pkg/dispatcher"
)
//Response 处理api返回值
func Response(conf *conf.MetadataConf) dispatcher.HandlerFunc {
return func(ctx *dispatcher.Context) {
ctx.Next()
nctx := getCTX(ctx)
if nctx == nil {
return
}
defer nctx.Close()
if err := nctx.Response.GetError(); err != nil {
getLogger(ctx).Errorf("err:%v", err)
if !servers.IsDebug {
nctx.Response.ShouldContent(errors.New("请求发生错误"))
}
}
if ctx.Writer.Written() {
return
}
tp, content, err := nctx.Response.GetJSONRenderContent()
writeTrace(getTrace(conf), tp, ctx, content)
if err != nil {
getLogger(ctx).Error(err)
ctx.JSON(nctx.Response.GetStatus(), map[string]interface{}{"err": err})
return
}
ctx.JSON(nctx.Response.GetStatus(), content)
// tpName := context.ContentTypes[tp]
// switch tp {
// case context.CT_XML:
// if v, ok := content.([]byte); ok {
// ctx.Data(nctx.Response.GetStatus(), tpName, v)
// return
// }
// ctx.XML(nctx.Response.GetStatus(), content)
// case context.CT_YMAL:
// if v, ok := content.([]byte); ok {
// ctx.Data(nctx.Response.GetStatus(), tpName, v)
// return
// }
// ctx.YAML(nctx.Response.GetStatus(), content)
// case context.CT_PLAIN, context.CT_HTML:
// if v, ok := content.([]byte); ok {
// ctx.Data(nctx.Response.GetStatus(), tpName, v)
// return
// }
// ctx.Data(nctx.Response.GetStatus(), tpName, ([]byte)(content.(string)))
// default:
// if v, ok := content.([]byte); ok {
// ctx.Data(nctx.Response.GetStatus(), tpName, v)
// return
// }
// ctx.JSON(nctx.Response.GetStatus(), content)
// }
}
}
func writeTrace(b bool, tp int, ctx *dispatcher.Context, c interface{}) {
if !b {
return
}
switch v := c.(type) {
case []byte:
setResponseRaw(ctx, string(v))
case string:
setResponseRaw(ctx, v)
default:
var buff = bytes.NewBufferString("")
switch tp {
case context.CT_XML:
xml.NewEncoder(buff).Encode(c)
default:
json.NewEncoder(buff).Encode(c)
}
setResponseRaw(ctx, strings.Trim(buff.String(), "\n"))
buff.Reset()
}
}