这是indexloc提供的服务,不要输入任何密码
Skip to content

Conversation

@gmtstephane
Copy link
Contributor

Hello,

I accidentally closed the last pull request #275 .

Are you talking about something like this in order to set the context ?

@x-user
Copy link
Contributor

x-user commented Mar 9, 2024

I think @danielgtaylor mean that it should be done on middleware level:

// middleware.go

type (
	contextKey struct{}

	humaContext huma.Context

	wrapper struct {
		humaContext
		custom context.Context
	}

	HumaMiddleware func(huma.Context, func(huma.Context))
)

const {
	requestIDKey = contextKey{}
}

var wrapperPool = sync.Pool{
	New: func() interface{} {
		return &wrapper{}
	},
}

func acquireWrapper() *wrapper {
	return wrapperPool.Get().(*wrapper)
}

func (w *wrapper) Context() context.Context {
	return w.custom
}

func Get(c huma.Context) string {
	ctx := c.Context()
	v := ctx.Value(requestIDKey)
	if v == nil {
		return ""
	} else {
		return v.(string)
	}
}

func New() HumaMiddleware {
	return func(c huma.Context, next func(huma.Context)) {
		w := acquireWrapper()
		w.humaContext = c
		w.custom = context.WithValue(c.Context(), requestIDKey, "request-id")
		defer wrapperPool.Put(w)

		next(w)
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants