feat: add rest/httpc to make http requests governacible (#1638)

* feat: change x-trace-id to traceparent to follow opentelemetry

* feat: add rest/httpc to make http requests governacible

* chore: remove blank lines
This commit is contained in:
Kevin Wan
2022-03-13 14:11:14 +08:00
committed by GitHub
parent fec908a19b
commit 3279a7ef0f
7 changed files with 164 additions and 6 deletions

View File

@@ -0,0 +1,28 @@
package internal
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/timex"
"go.opentelemetry.io/otel/propagation"
)
func LogInterceptor(r *http.Request) (*http.Request, ResponseHandler) {
start := timex.Now()
return r, func(resp *http.Response) {
duration := timex.Since(start)
var tc propagation.TraceContext
ctx := tc.Extract(r.Context(), propagation.HeaderCarrier(resp.Header))
logger := logx.WithContext(ctx).WithDuration(duration)
if isOkResponse(resp.StatusCode) {
logger.Infof("[HTTP] %d - %s %s/%s", resp.StatusCode, r.Method, r.Host, r.RequestURI)
} else {
logger.Errorf("[HTTP] %d - %s %s/%s", resp.StatusCode, r.Method, r.Host, r.RequestURI)
}
}
}
func isOkResponse(code int) bool {
return code < http.StatusBadRequest
}