feat: retrieve values from context

This commit is contained in:
Kevin Franklin Kim 2022-07-26 08:49:31 +02:00
parent d8e1741be1
commit e6596bf2d1
2 changed files with 15 additions and 1 deletions

View File

@ -4,6 +4,7 @@ import (
"net/http"
"github.com/foomo/keel"
"github.com/foomo/keel/log"
keelhttp "github.com/foomo/keel/net/http"
"github.com/foomo/keel/net/http/middleware"
"github.com/foomo/keel/net/http/roundtripware"
@ -25,6 +26,7 @@ func main() {
// create demo service
svs := http.NewServeMux()
svs.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
l := log.WithHTTPRequest(l, r)
// send internal http request
if req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, "http://localhost:8080/internal", nil); err != nil {
httputils.InternalServerError(l, w, r, err)
@ -35,10 +37,12 @@ func main() {
} else {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(r.Header.Get(keelhttp.HeaderXRequestID) + " - " + resp.Header.Get(keelhttp.HeaderXRequestID)))
log.WithHTTPRequestOut(l, req).Info("sent internal request")
}
})
svs.HandleFunc("/internal", func(w http.ResponseWriter, r *http.Request) {
l.Info("internal: " + r.Header.Get(keelhttp.HeaderXRequestID))
l := log.WithHTTPRequest(l, r)
l.Info("handled internal request")
w.WriteHeader(http.StatusOK)
})

View File

@ -9,6 +9,8 @@ import (
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
keelhttpcontext "github.com/foomo/keel/net/http/context"
)
func With(l *zap.Logger, fields ...zap.Field) *zap.Logger {
@ -54,9 +56,13 @@ func WithHTTPRequest(l *zap.Logger, r *http.Request) *zap.Logger {
}
if id := r.Header.Get("X-Request-ID"); id != "" {
fields = append(fields, FHTTPRequestID(id))
} else if id, ok := keelhttpcontext.GetRequestID(r.Context()); ok && id != "" {
fields = append(fields, FHTTPRequestID(id))
}
if id := r.Header.Get("X-Session-ID"); id != "" {
fields = append(fields, FHTTPSessionID(id))
} else if id, ok := keelhttpcontext.GetSessionID(r.Context()); ok && id != "" {
fields = append(fields, FHTTPSessionID(id))
}
if r.TLS != nil {
fields = append(fields, FHTTPScheme("https"))
@ -106,9 +112,13 @@ func WithHTTPRequestOut(l *zap.Logger, r *http.Request) *zap.Logger {
}
if id := r.Header.Get("X-Request-ID"); id != "" {
fields = append(fields, FHTTPRequestID(id))
} else if id, ok := keelhttpcontext.GetRequestID(r.Context()); ok && id != "" {
fields = append(fields, FHTTPRequestID(id))
}
if id := r.Header.Get("X-Session-ID"); id != "" {
fields = append(fields, FHTTPSessionID(id))
} else if id, ok := keelhttpcontext.GetSessionID(r.Context()); ok && id != "" {
fields = append(fields, FHTTPSessionID(id))
}
if r.TLS != nil {
fields = append(fields, FHTTPScheme("https"))