Documentation
¶
Index ¶
- Variables
- func ApplyCachedDNS(urlStr string) (string, func(), error)
- func GuessContentTypeFromFilename(filename string) string
- func HTTPRequest(ctx context.Context, method string, urlStr string, body io.Reader, ...) (*http.Response, error)
- func JSONRequest(ctx context.Context, method string, url string, body any, headers http.Header, ...) (http.Header, int, error)
- func ParseMultipartForm(header http.Header, body io.Reader, ...) error
- func RespondJSON(resp http.ResponseWriter, data any)
- func SetContextExtractor(fn contextExtractorFn)
- func SetParamExtractor(fn paramExtractorFn)
- func SniffContentType(filename string, data io.ReadCloser) (io.ReadCloser, string, error)
- func UnmarshalHTTPRequest(into any, r *http.Request) error
- func UnrestrictedCORS(handler http.Handler) http.Handler
- type FormFieldUnmarshaler
- type HTTPClient
- type HTTPHeaderUnmarshaler
- type MultipartFile
- type MultipartPart
- type RouteParamUnmarshaler
- type URLPathUnmarshaler
- type URLQueryUnmarshaler
Constants ¶
This section is empty.
Variables ¶
var LogHTTPRequests bool
LogHTTPRequests controls whether HTTP requests and responses are logged to stdout. When set to true, request dumps and response status codes will be printed.
Functions ¶
func ApplyCachedDNS ¶
ApplyCachedDNS resolves the hostname in the given URL using a cached DNS lookup and returns a modified URL with the IP address substituted for the hostname. It also returns a cleanup function that removes the cached entry for the hostname.
func HTTPRequest ¶
func HTTPRequest(ctx context.Context, method string, urlStr string, body io.Reader, headers http.Header) (*http.Response, error)
HTTPRequest performs an HTTP request with the given method, URL, body, and headers. It uses cached DNS resolution and will clear the DNS cache for the hostname if a URL error occurs. If LogHTTPRequests is true, it will log the request and response details to stdout.
func JSONRequest ¶
func JSONRequest(ctx context.Context, method string, url string, body any, headers http.Header, response any) (http.Header, int, error)
JSONRequest performs an HTTP request with JSON encoding/decoding. It marshals the body parameter to JSON, sends the request with appropriate Content-Type and Accept headers, and unmarshals the response into the response parameter. It returns the response headers, status code, and any error encountered.
func ParseMultipartForm ¶
func ParseMultipartForm(header http.Header, body io.Reader, fn func(field string, part *multipart.Part) error) error
ParseMultipartForm parses a multipart form from the given header and body, invoking the provided callback function for each part. The callback receives the form field name and the part itself. Parsing stops on the first error returned by the callback.
func RespondJSON ¶
func RespondJSON(resp http.ResponseWriter, data any)
RespondJSON encodes the given data as JSON and writes it to the response writer with the appropriate Content-Type header. It panics if encoding fails.
func SetContextExtractor ¶
func SetContextExtractor(fn contextExtractorFn)
SetContextExtractor configures a custom function for extracting values from request contexts. This is used when unmarshaling fields tagged with ctx:"key". The default implementation uses context.Context.Value(key), but frameworks may need custom extraction logic.
func SetParamExtractor ¶
func SetParamExtractor(fn paramExtractorFn)
SetParamExtractor configures a custom function for extracting URL path parameters. This is used when unmarshaling fields tagged with param:"name". Different routing frameworks (e.g., chi, gorilla/mux, gin) have different APIs for accessing path parameters, so this function must be set to match your router's API.
func SniffContentType ¶
func SniffContentType(filename string, data io.ReadCloser) (io.ReadCloser, string, error)
func UnmarshalHTTPRequest ¶
UnmarshalHTTPRequest extracts data from an HTTP request into a struct using struct tags. The into parameter must be a pointer to a struct. Supported tags include:
- header:"Header-Name" - extracts from request headers
- query:"param" - extracts from URL query parameters
- path:"pattern" - extracts the URL path
- param:"name" - extracts URL path parameters (requires SetParamExtractor)
- ctx:"key" - extracts from request context (requires SetContextExtractor)
- form:"field" - extracts from form data (application/x-www-form-urlencoded or multipart/form-data)
- file:"field" - extracts file uploads as *MultipartFile or []*MultipartFile
- body:"json" - unmarshals request body as JSON
- required:"true" - makes the field required (returns error if missing)
Fields can be strings, integers, booleans, slices, or types implementing custom unmarshalers.
Example usage:
type CreateUserRequest struct {
UserID string `param:"id" required:"true"`
Name string `form:"name" required:"true"`
Email string `form:"email"`
Age int `form:"age"`
Tags []string `query:"tag"`
ContentType string `header:"Content-Type"`
Avatar *MultipartFile `file:"avatar"`
}
func HandleCreateUser(w http.ResponseWriter, r *http.Request) {
var req CreateUserRequest
if err := UnmarshalHTTPRequest(&req, r); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Use req.UserID, req.Name, etc.
if req.Avatar != nil {
defer req.Avatar.Close()
// Process uploaded file...
}
}
For JSON body unmarshaling:
type UpdateSettingsRequest struct {
Settings map[string]any `body:"json"`
}
For multiple file uploads:
type UploadRequest struct {
Images []*MultipartFile `file:"images"`
}
For slice query parameters (?tag=foo&tag=bar):
type SearchRequest struct {
Tags []string `query:"tag"`
}
Types ¶
type FormFieldUnmarshaler ¶
FormFieldUnmarshaler is implemented by types that can unmarshal themselves from a form field value. When a struct field implements this interface and is tagged with form:"field", this method will be called instead of the default string conversion.
type HTTPClient ¶
HTTPClient extends http.Client with automatic idle connection reaping capabilities. It includes a stop channel for graceful shutdown of the connection reaping goroutine.
func MakeHTTPClient ¶
func MakeHTTPClient(requestTimeout, reapIdleConnsInterval time.Duration, cookieJar http.CookieJar, tlsCerts []tls.Certificate) *HTTPClient
MakeHTTPClient creates a new HTTPClient with the specified configuration. The requestTimeout sets the maximum duration for requests. If reapIdleConnsInterval is greater than 0, a goroutine will periodically close idle connections at the specified interval. The client uses TLS 1.3 only and accepts the provided TLS certificates for client authentication.
func (HTTPClient) Close ¶
func (c HTTPClient) Close()
Close stops the idle connection reaping goroutine by closing the stop channel.
type HTTPHeaderUnmarshaler ¶
HTTPHeaderUnmarshaler is implemented by types that can unmarshal themselves from an HTTP header value. When a struct field implements this interface and is tagged with header:"Header-Name", this method will be called instead of the default string conversion.
type MultipartFile ¶
type MultipartFile struct {
File multipart.File
Header *multipart.FileHeader
}
MultipartFile wraps a multipart file upload with its associated metadata header. It provides access to both the file contents and metadata such as filename, size, and MIME type through the Header field.
func (*MultipartFile) Close ¶
func (mf *MultipartFile) Close() error
Close closes the underlying file, releasing any associated resources.
type MultipartPart ¶
type MultipartPart struct {
Part *multipart.Part
Body io.ReadCloser
}
MultipartPart wraps a multipart.Part and its associated body reader, implementing io.ReadCloser. It ensures both the part and body are properly closed.
func (*MultipartPart) Close ¶
func (mp *MultipartPart) Close() error
Close implements io.Closer by closing both the Part and Body, returning the first error encountered if any.
type RouteParamUnmarshaler ¶
RouteParamUnmarshaler is implemented by types that can unmarshal themselves from a URL route parameter. When a struct field implements this interface and is tagged with param:"name", this method will be called instead of the default string conversion.
type URLPathUnmarshaler ¶
URLPathUnmarshaler is implemented by types that can unmarshal themselves from a URL path string. When a struct field implements this interface and is tagged with path:"", this method will be called instead of the default string conversion.
type URLQueryUnmarshaler ¶
URLQueryUnmarshaler is implemented by types that can unmarshal themselves from URL query parameter values. When a struct field implements this interface and is tagged with query:"param", this method will be called with all values for that query parameter instead of the default conversion.