Skip to content

Commit

Permalink
Merge pull request #659 from excavador/main
Browse files Browse the repository at this point in the history
Propagate fiberCtx.UserContext() to huma.Context - Context()
  • Loading branch information
danielgtaylor authored Dec 2, 2024
2 parents bfe8892 + f355429 commit 1c8e5c9
Showing 1 changed file with 34 additions and 1 deletion.
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

0 comments on commit 1c8e5c9

Please sign in to comment.