This commit is contained in:
parent
c18b6059f3
commit
c5fd71b542
@ -6,8 +6,9 @@ import (
|
||||
"github.com/nacos-group/nacos-sdk-go/clients/config_client"
|
||||
"github.com/nacos-group/nacos-sdk-go/clients/naming_client"
|
||||
"github.com/nacos-group/nacos-sdk-go/vo"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@ -59,33 +60,17 @@ func (n nacosClient) Remote(ctx *gin.Context) {
|
||||
apiHost = fmt.Sprintf("%s:%v", instance.Ip, instance.Port)
|
||||
}
|
||||
|
||||
// 组装内部接口
|
||||
apiUrl := fmt.Sprintf("http://%v%v", apiHost, uri)
|
||||
// 创建Request对象
|
||||
req, err := http.NewRequest(ctx.Request.Method, apiUrl, ctx.Request.Body)
|
||||
if err != nil {
|
||||
Log.Error("请求异常: %v\n", err)
|
||||
ctx.String(http.StatusBadGateway, "请求异常: %v", err.Error())
|
||||
return
|
||||
u := &url.URL{
|
||||
Scheme: "http",
|
||||
Host: apiHost,
|
||||
}
|
||||
// 填充Form参数(大概率用不上)
|
||||
req.Form = ctx.Request.Form
|
||||
// 填充链路追踪标记
|
||||
req.Header.Add("uber-trace-id", ctx.GetString("UberTraceId"))
|
||||
// 请求ID
|
||||
req.Header.Add("X-Request-Id", ctx.GetString("X-Request-Id"))
|
||||
// 设置来源
|
||||
req.Header.Add("From", "internal")
|
||||
// 发起请求
|
||||
client := &http.Client{}
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
Log.Error("请求异常: %v\n", err)
|
||||
ctx.String(http.StatusBadGateway, "请求异常:%v", err.Error())
|
||||
return
|
||||
proxy := httputil.NewSingleHostReverseProxy(u)
|
||||
ctx.Request.Header.Add("From", "internal")
|
||||
ctx.Request.Header.Add("uber-trace-id", ctx.GetString("UberTraceId"))
|
||||
// 重写错误回调
|
||||
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
Log.Error("代理转发错误: %v", err.Error())
|
||||
ctx.String(http.StatusInternalServerError, "系统内部错误")
|
||||
}
|
||||
// 返回结果到前端
|
||||
sss, _ := ioutil.ReadAll(response.Body)
|
||||
Log.Debug(string(sss))
|
||||
ctx.String(response.StatusCode, string(sss))
|
||||
proxy.ServeHTTP(ctx.Writer, ctx.Request)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user