sync from project
This commit is contained in:
@ -2,7 +2,10 @@ package magic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"git.jeffthecoder.xyz/public/lazyhandler/middleware/cleanup"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@ -12,4 +15,49 @@ func init() {
|
||||
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
|
||||
})
|
||||
}
|
||||
|
Reference in New Issue
Block a user