wip: add more middleware examples

This commit is contained in:
AJ ONeal 2026-01-13 03:03:34 -07:00
parent c5e2159d5e
commit 939c733ace
No known key found for this signature in database
3 changed files with 58 additions and 3 deletions

View File

@ -89,6 +89,27 @@ func recoverPanics(next http.Handler) http.Handler {
}
```
#### Example: Panic handler
```go
func RecoverPanics(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer func() {
if _err := recover(); _err != nil {
err, ok := _err.(error)
if !ok {
err = fmt.Errorf("%v", _err)
}
api.InternalError(w, r, err)
return
}
}()
next.ServeHTTP(w, r)
}
}
```
#### Example: Request logger
```go
@ -121,7 +142,10 @@ func basicAuth(next http.Handler) http.Handler {
return
}
next.ServeHTTP(w, r)
ctx := r.Context()
ctx = context.WithValue(ctx, UsernameKey, username)
next.ServeHTTP(w, r.WithContext(ctx))
// or just next.ServeHTTP(w, r)
}
}
```

View File

@ -0,0 +1,30 @@
package middleware
import (
"context"
"net/http"
)
type BasicAuthVerifier interface {
Verify(string, string) bool
}
type usernameKeyType struct{}
var UsernameKey usernameKeyType
func BasicAuth(v BasicAuthVerifier) func(http.HandlerFunc) http.HandlerFunc {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if !ok || !v.Verify(username, password) {
// s.jsonError(w, http.StatusUnauthorized, "unauthorized", "Unauthorized", "Invalid credentials")
return
}
ctx := r.Context()
ctx = context.WithValue(ctx, UsernameKey, username)
next.ServeHTTP(w, r.WithContext(ctx))
}
}
}

View File

@ -12,6 +12,7 @@
package middleware
import (
"errors"
"net/http"
"slices"
)
@ -33,7 +34,7 @@ type MiddlewareChain struct {
// Handle composes middleware with the final handler
func (c MiddlewareChain) Handle(handler http.Handler) http.Handler {
if handler == nil {
panic("mw.New(...).Use(...).Handle(-->this<--) requires a handler")
panic(errors.New("mw.New(...).Use(...).Handle(-->this<--) requires a handler"))
}
middlewares := make([]Middleware, len(c.middlewares))
@ -86,7 +87,7 @@ func (c MiddlewareMux) HandleFunc(path string, handler http.HandlerFunc) {
// Handle composes middleware with the final handler
func (c MiddlewareMux) handle(handler http.Handler) http.Handler {
if handler == nil {
panic("mw.New(...).Use(...).Handle(-->this<--) requires a handler")
panic(errors.New("mw.New(...).Use(...).Handle(-->this<--) requires a handler"))
}
middlewares := make([]Middleware, len(c.middlewares))