1 Star 0 Fork 0

leminewx / leego

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
context_goway.go 2.22 KB
一键复制 编辑 原始数据 按行查看 历史
leminewx 提交于 2023-09-09 14:39 . 优化处理Goway的上下文代码
package leego
import (
"fmt"
"io"
"net/http"
"strings"
)
var (
GowayTracer = http.CanonicalHeaderKey("Goway-Tracer")
GowayServer = http.CanonicalHeaderKey("Goway-Server")
)
type OptionGoway struct {
// 环境 (必选)
Env string
// 应用 ID (必选)
AppId string
// 应用版本 (可选)
AppVer string
// 实例 ID (可选)
InstanceId string
}
// RequestByGoway 尝试通过 Goway 网关发起请求
func (own *Context) RequestByGoway(method, url string, headers map[string]string, optGoway OptionGoway, body io.Reader) (*http.Response, error) {
if optGoway.Env == "" || optGoway.AppId == "" {
return nil, fmt.Errorf("nil goway gateway")
}
var server string
if optGoway.AppVer == "" {
if optGoway.InstanceId != "" {
server = fmt.Sprintf("%s, %s, %s, %s", optGoway.Env, optGoway.AppId, optGoway.AppVer, optGoway.InstanceId)
} else {
server = fmt.Sprintf("%s, %s, %s", optGoway.Env, optGoway.AppId, optGoway.AppVer)
}
} else {
server = fmt.Sprintf("%s, %s", optGoway.Env, optGoway.AppId)
}
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
for key, val := range headers {
req.Header.Set(key, val)
}
req.Header.Set(GowayServer, server)
req.Header.Set(GowayTracer, own.Headers.Get(GowayTracer))
return http.DefaultClient.Do(req)
}
// GetGowayTracer 尝试获取 Goway 网关中的的链路 ID:trace id 和 span id
func (own *Context) GetGowayTracer() (tid, sid string) {
info := strings.Split(own.Headers.Get(GowayTracer), ", ")
if len(info) == 1 {
return info[0], ""
}
if len(info) > 1 {
return info[0], info[1]
}
return
}
// GetGowayServer 尝试获取 Goway 网关的代理数据:env, app id, app ver, instance id
func (own *Context) GetGowayServer() (env, appId, appVer, instanceId string) {
info := strings.Split(own.Headers.Get(GowayServer), ", ")
switch len(info) {
case 0: // 未指定任何信息
return
case 1: // 只指定环境
env = info[0]
case 2: // 指定应用环境和ID
env = info[0]
appId = info[1]
case 3: // 指定应用环境、ID和版本
env = info[0]
appId = info[1]
appVer = info[2]
default: // 指定应用环境、ID、版本和实例ID
env = info[0]
appId = info[1]
appVer = info[2]
instanceId = info[3]
}
return
}
Go
1
https://gitee.com/leminewx/leego.git
git@gitee.com:leminewx/leego.git
leminewx
leego
leego
4d7864a3835c

搜索帮助

53164aa7 5694891 3bd8fe86 5694891