-
Notifications
You must be signed in to change notification settings - Fork 3
/
httpHandler.go
35 lines (32 loc) · 1.29 KB
/
httpHandler.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
package webapi
import (
"github.com/farseer-go/fs/asyncLocal"
"github.com/farseer-go/fs/container"
"github.com/farseer-go/fs/flog"
"github.com/farseer-go/fs/trace"
"github.com/farseer-go/webapi/context"
"net/http"
)
func HttpHandler(route *context.HttpRoute) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 解析报文、组装httpContext
httpContext := context.NewHttpContext(route, w, r)
// 创建链路追踪上下文
trackContext := container.Resolve[trace.IManager]().EntryWebApi(httpContext.URI.Host, httpContext.URI.Url, httpContext.Method, httpContext.ContentType, httpContext.Header.ToMap(), httpContext.URI.GetRealIp())
// 记录出入参
defer func() {
trackContext.SetBody(httpContext.Request.BodyString, httpContext.Response.GetHttpCode(), string(httpContext.Response.BodyBytes))
trackContext.End(httpContext.Exception)
}()
httpContext.Data.Set("Trace", trackContext)
// 设置到routine,可用于任意子函数获取
context.RoutineHttpContext.Set(httpContext)
// 执行第一个中间件
route.HttpMiddleware.Invoke(httpContext)
// 记录异常
if httpContext.Exception != nil {
_ = flog.Errorf("[%s]%s 发生错误:%s", httpContext.Method, httpContext.URI.Url, httpContext.Exception.Error())
}
asyncLocal.Release()
}
}