-
Notifications
You must be signed in to change notification settings - Fork 97
/
component.rpc.go
85 lines (76 loc) · 2.29 KB
/
component.rpc.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
package component
import (
"fmt"
"strings"
"github.com/micro-plat/hydra/context"
"github.com/micro-plat/lib4go/types"
)
//NewRPCCtxSerivce 构建RPC转发请求
func NewRPCCtxSerivce(rpcServiceName string, rpcInput ...func(ctx *context.Context) interface{}) ServiceFunc {
return func(ctx *context.Context) (rs interface{}) {
header, _ := ctx.Request.Http.GetHeader()
cookie, _ := ctx.Request.Http.GetCookies()
for k, v := range cookie {
header[k] = v
}
header["method"] = strings.ToUpper(ctx.Request.GetMethod())
nheader := types.NewXMapBySMap(header)
input := types.NewXMapByMap(ctx.Request.GetRequestMap())
switch {
case len(rpcInput) == 1:
value := rpcInput[0](ctx)
switch v := value.(type) {
case context.IError, error:
return value
case map[string]string:
input.MergeSMap(v)
case map[string]interface{}:
input.MergeMap(v)
default:
return fmt.Errorf("执NewRPCCtxSerivce服务返回的类型只支持map[string]string,map[string]interface{}")
}
}
status, result, params, err := ctx.RPC.Request(rpcServiceName, nheader.ToSMap(), input.ToMap(), true)
if err != nil {
return err
}
ctx.Response.SetParams(types.GetIMap(params))
if status != 200 {
return context.NewError(status, result)
}
ctx.Response.SetJSON()
ctx.Response.MustContent(status, result)
return
}
}
//NewRPCSerivce 构建RPC转发请求
func NewRPCSerivce(rpcServiceName string, rpcInput ...map[string]string) ServiceFunc {
return func(ctx *context.Context) (rs interface{}) {
header, _ := ctx.Request.Http.GetHeader()
cookie, _ := ctx.Request.Http.GetCookies()
for k, v := range cookie {
header[k] = v
}
header["method"] = strings.ToUpper(ctx.Request.GetMethod())
nheader := types.NewXMapBySMap(header)
input := types.NewXMapByMap(ctx.Request.GetRequestMap())
switch {
case len(rpcInput) == 1:
input.MergeSMap(rpcInput[0])
case len(rpcInput) >= 2:
nheader.MergeSMap(rpcInput[0])
input.MergeSMap(rpcInput[1])
}
status, result, params, err := ctx.RPC.Request(rpcServiceName, nheader.ToSMap(), input.ToMap(), true)
if err != nil {
return err
}
ctx.Response.SetParams(types.GetIMap(params))
if status != 200 {
return context.NewError(status, result)
}
ctx.Response.SetJSON()
ctx.Response.MustContent(status, result)
return
}
}