Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Propagate fiberCtx.UserContext() to huma.Context - Context() #659

Merged
merged 1 commit into from
Dec 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion adapters/humafiber/humafiber.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,35 @@ import (
"github.com/gofiber/fiber/v2"
)

// avoid race condition inside fasthttp need to cache Context().Done() and UserContext().Value
type contextAdapter struct {
*fiber.Ctx
done <-chan struct{}
user func(any) any
}

var _ context.Context = &contextAdapter{}

func (ca *contextAdapter) Deadline() (deadline time.Time, ok bool) {
return ca.Ctx.Context().Deadline()
}

func (ca *contextAdapter) Done() <-chan struct{} {
return ca.done
}

func (ca *contextAdapter) Err() error {
return ca.Ctx.Context().Err()
}

func (ca *contextAdapter) Value(key any) any {
var value = ca.user(key)
if value != nil {
return value
}
return ca.Ctx.Context().Value(key)
}

type fiberCtx struct {
op *huma.Operation
orig *fiber.Ctx
Expand All @@ -33,7 +62,11 @@ func (c *fiberCtx) Matched() string {
}

func (c *fiberCtx) Context() context.Context {
return c.orig.Context()
return &contextAdapter{
Ctx: c.orig,
done: c.orig.Context().Done(),
user: c.orig.UserContext().Value,
}
}

func (c *fiberCtx) Method() string {
Expand Down
Loading