diff --git a/ctx.go b/ctx.go index 5a30b98..1645310 100644 --- a/ctx.go +++ b/ctx.go @@ -2,9 +2,11 @@ package nf import ( "bytes" + "context" "encoding/json" "errors" "fmt" + "github.com/google/uuid" "github.com/loveuer/nf/internal/sse" "io" "mime/multipart" @@ -38,8 +40,18 @@ type Ctx struct { func newContext(app *App, writer http.ResponseWriter, request *http.Request) *Ctx { - skippedNodes := make([]skippedNode, 0, app.maxSections) - v := make(Params, 0, app.maxParams) + var ( + traceId string + skippedNodes = make([]skippedNode, 0, app.maxSections) + v = make(Params, 0, app.maxParams) + ) + + if traceId = request.Header.Get(TraceKey); traceId == "" { + traceId = uuid.Must(uuid.NewV7()).String() + } + + c := context.WithValue(request.Context(), TraceKey, traceId) + request.WithContext(c) ctx := &Ctx{ lock: sync.Mutex{}, @@ -112,6 +124,10 @@ func (c *Ctx) Cookies(key string, defaultValue ...string) string { return cookie.Value } +func (c *Ctx) Context() context.Context { + return c.Request.Context() +} + func (c *Ctx) Next() error { c.index++ diff --git a/nf.go b/nf.go index 653e939..3f701d5 100644 --- a/nf.go +++ b/nf.go @@ -1,10 +1,11 @@ package nf const ( - banner = " _ _ _ ___ _ \n | \\| |___| |_ | __|__ _ _ _ _ __| |\n | .` / _ \\ _| | _/ _ \\ || | ' \\/ _` |\n |_|\\_\\___/\\__| |_|\\___/\\_,_|_||_\\__,_|\n " - _404 = "Not Found" - _405 = `405 Method Not Allowed` - _500 = `500 Internal Server Error` + banner = " _ _ _ ___ _ \n | \\| |___| |_ | __|__ _ _ _ _ __| |\n | .` / _ \\ _| | _/ _ \\ || | ' \\/ _` |\n |_|\\_\\___/\\__| |_|\\___/\\_,_|_||_\\__,_|\n " + _404 = "Not Found" + _405 = `405 Method Not Allowed` + _500 = `500 Internal Server Error` + TraceKey = "X-Trace-Id" ) type Map map[string]interface{}