danielgtaylor / danielgtaylor/huma
Setting headers in error response always appends
- Dominant language
- Go
- Stars
- 4.4k
- Forks
- 285
- Avg merge
- 40m
- Merged PRs (30d)
- 1
Description
@danielgtaylor @victoraugustolls Thanks for the prototype solution in #386 and #387 for setting headers in error responses.
While it worked well initially, I've hit a case where I don't see solution. I'm happy to open a PR, but would appreciate your thoughts on the right approach to solve this specific issue. I know there are thoughts around a much more robust approach. At this point, I'm only trying to solve this narrow problem.
I'm implementing a route-specific secondary rate limiter (after a general IP-based limiter as middleware) that exponentially increases the required time between password resets based on the POSTed email address.
The issue is that, unlike headers in output structs, headers in errors are always appended. This means that I can't override the headers set by the general limiter with the headers set by the more restrictive limiter. The response with duplicate headers looks like this:
```
HTTP/1.1 429 Too Many Requests
Connection: close
Content-Type: application/problem+json
Link: ; rel="describedBy"
Retry-After: Mon, 10 Jun 2024 13:37:46 UTC
Retry-After: Mon, 10 Jun 2024 13:38:47 UTC
X-Ratelimit-Limit: 100
X-Ratelimit-Limit: 1
X-Ratelimit-Remaining: 98
X-Ratelimit-Remaining: 0
X-Ratelimit-Reset: 2024-06-10T13:37:47Z
X-Ratelimit-Reset: 2024-06-11T13:37:46Z
X-Ratelimit-Retry: 2024-06-10T13:37:46Z
X-Ratelimit-Retry: 2024-06-10T13:38:47Z
```
Ideally, in this case, I could do something like the array approach documented for output structs -- override if a single value and append when an array. But I understand that in the general case it makes more sense to alway append error headers to preserve information that might be useful when troubleshooting.
It seems that:
- There is no way to control appending vs overriding error headers.
- There is no way to access headers in the handler to remove duplicates since the request isn't available.
- A transformer can't be used to remove duplicate headers since there is no way to the read the response headers (only the request headers) from the Huma context.
Other than a framework-level enhancement, the only things I can think of doing are:
- Move the secondary limiter into a middleware and parse the body before Huma does to get at the properties I need to configure the secondary limiter attempt. In addition to parsing the body twice, it would not benefit from Huma's validation and it would separate part of the logic from the handler into a middleware.
- Wrap the Huma context in the middleware to override AppendHeader() with SetHeader() for specific headers.
Thoughts?
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.