Files
lazyhandler/magic/request.go
2025-06-18 10:12:19 +08:00

64 lines
1.9 KiB
Go

package magic
import (
"context"
"io"
"net/http"
"git.jeffthecoder.xyz/public/lazyhandler/middleware/cleanup"
)
func init() {
RegisterExtractorGeneric[*http.Request](func(r *http.Request) (any, error) {
return r, nil
})
RegisterExtractorGeneric[context.Context](func(r *http.Request) (any, error) {
return r.Context(), nil
})
// RegisterExtractorThatTakesBodyGeneric for io.ReadCloser extracts the request body.
//
// IMPORTANT: This extractor consumes the request body (r.Body). After this extractor
// is used, r.Body will be set to nil to prevent it from being read multiple times.
// Any subsequent attempt to read the body will fail.
//
// A cleanup function is automatically registered to close the body once the request
// is finished. This requires the cleanup middleware to be present in the handler chain.
RegisterExtractorThatTakesBodyGeneric[io.ReadCloser](func(r *http.Request) (any, error) {
if r.Body == nil {
panic("body is already taken")
}
body := r.Body
r.Body = nil
cleanup.Register(r.Context(), cleanup.CleanupFunc(func() {
body.Close()
}))
return body, nil
})
// RegisterExtractorThatTakesBodyGeneric for io.Reader extracts the request body.
//
// IMPORTANT: This extractor consumes the request body (r.Body). After this extractor
// is used, r.Body will be set to nil to prevent it from being read multiple times.
// Any subsequent attempt to read the body will fail.
//
// A cleanup function is automatically registered to close the body once the request
// is finished. This requires the cleanup middleware to be present in the handler chain.
RegisterExtractorThatTakesBodyGeneric[io.Reader](func(r *http.Request) (any, error) {
if r.Body == nil {
panic("body is already taken")
}
body := r.Body
r.Body = nil
cleanup.Register(r.Context(), cleanup.CleanupFunc(func() {
body.Close()
}))
return body, nil
})
}