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

Question about huma.WriteErr #715

Open
NeroBlackstone opened this issue Jan 24, 2025 · 1 comment
Open

Question about huma.WriteErr #715

NeroBlackstone opened this issue Jan 24, 2025 · 1 comment
Labels
question Further information is requested

Comments

@NeroBlackstone
Copy link
Contributor

In huma middleware docs.

I don't know where dose the variable api come from?

func MyMiddleware(ctx huma.Context, next func(ctx huma.Context)) {
	// If there is a query parameter "error=true", then return an error
	if ctx.Query("error") == "true" {
               // WHERE DOSE THE VARIABLE API COME FROM
		huma.WriteErr(api, ctx, http.StatusInternalServerError,
			"Some friendly message", fmt.Errorf("error detail"),
		)
		return
	}

	// Otherwise, just continue as normal.
	next(ctx)
})
@danielgtaylor danielgtaylor added the question Further information is requested label Feb 4, 2025
@danielgtaylor
Copy link
Owner

danielgtaylor commented Feb 4, 2025

@NeroBlackstone you can pass it into the middleware creation function. This creates a closure where you have access to the API. For example, this prints the API title in a middleware:

func MyMiddleware(api huma.API) func(ctx huma.Context, next func(huma.Context)) {
	return func(ctx huma.Context, next func(huma.Context)) {
		fmt.Println("Hello from middleware for " + api.OpenAPI().Info.Title)
		next(ctx)
	}
}

https://go.dev/play/p/khcUijO0D34

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants