forked from wanghongfei/gogate
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server_request.go
77 lines (59 loc) · 1.51 KB
/
server_request.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
package server
import (
"errors"
"strings"
asynclog "github.com/alecthomas/log4go"
"github.com/valyala/fasthttp"
"github.com/wanghongfei/gogate/utils"
)
// 转发请求到指定微服务
func (serv *Server) sendRequest(ctx *fasthttp.RequestCtx, req *fasthttp.Request) (*fasthttp.Response, error) {
// 获取服务信息
info := ctx.UserValue(ROUTE_INFO).(*ServiceInfo)
var c *fasthttp.LBClient
// 需要从注册列表中查询地址
if info.Id != "" {
// 获取Client
appId := info.Id
// 灰度, 选择版本
version := chooseVersion(info.Canary)
// 构造HTTP client名
clientName := appId
if "" != version {
clientName = clientName + ":" + version
}
client, exist := serv.proxyClients.Get(clientName)
if !exist {
return nil, errors.New("no client " + clientName + " for service " + appId + ", (service is offline)")
}
c = client
} else {
// 直接使用后面的地址
hostList := strings.Split(info.Host, ",")
c = &fasthttp.LBClient{
Clients: createClients(hostList),
}
}
// 发请求
resp := new(fasthttp.Response)
err := c.Do(req, resp)
if nil != err {
return nil, err
}
return resp, nil
}
func chooseVersion(canaryInfos []*CanaryInfo) string {
if nil == canaryInfos || len(canaryInfos) == 0 {
return ""
}
var weights []int
for _, info := range canaryInfos {
weights = append(weights, info.Weight)
}
index := utils.RandomByWeight(weights)
if -1 == index {
asynclog.Warn("random interval returned -1")
return ""
}
return canaryInfos[index].Meta
}