Add NewFormRequest for form-encoded HTTP requests
Creates requests with application/x-www-form-urlencoded body from url.Values. Supports GetBody for retry compatibility, following the same pattern as NewJSONRequest. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
18
request.go
18
request.go
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// NewRequest creates an http.Request with context. It is a convenience
|
||||
@@ -32,3 +33,20 @@ func NewJSONRequest(ctx context.Context, method, url string, body any) (*http.Re
|
||||
}
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// NewFormRequest creates an http.Request with a form-encoded body and
|
||||
// sets Content-Type to application/x-www-form-urlencoded.
|
||||
// The GetBody function is set so that the request can be retried.
|
||||
func NewFormRequest(ctx context.Context, method, rawURL string, values url.Values) (*http.Request, error) {
|
||||
encoded := values.Encode()
|
||||
b := []byte(encoded)
|
||||
req, err := http.NewRequestWithContext(ctx, method, rawURL, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.GetBody = func() (io.ReadCloser, error) {
|
||||
return io.NopCloser(bytes.NewReader(b)), nil
|
||||
}
|
||||
return req, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user