-
-
Notifications
You must be signed in to change notification settings - Fork 158
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #134 from Insei/middlewares
huma: v2: add middlewares support
- Loading branch information
Showing
4 changed files
with
84 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
package huma | ||
|
||
type Middlewares []func(ctx Context, next func(Context)) | ||
|
||
// Handler builds and returns a handler func from the chain of middlewares, | ||
// with `endpoint func` as the final handler. | ||
func (m Middlewares) Handler(endpoint func(Context)) func(Context) { | ||
return m.chain(endpoint) | ||
} | ||
|
||
// wrap user middleware func with the next func to one func | ||
func wrap(fn func(Context, func(Context)), next func(Context)) func(Context) { | ||
return func(ctx Context) { | ||
fn(ctx, next) | ||
} | ||
} | ||
|
||
// chain builds a Middleware composed of an inline middleware stack and endpoint | ||
// handler in the order they are passed. | ||
func (m Middlewares) chain(endpoint func(Context)) func(Context) { | ||
// Return ahead of time if there aren't any middlewares for the chain | ||
if len(m) == 0 { | ||
return endpoint | ||
} | ||
|
||
// Wrap the end handler with the middleware chain | ||
w := wrap(m[len(m)-1], endpoint) | ||
for i := len(m) - 2; i >= 0; i-- { | ||
w = wrap(m[i], w) | ||
} | ||
return w | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters