bhttp

package
v0.0.0-...-a929fdb Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 21, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
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

func ApplyCachedDNS(urlStr string) (string, func(), error)

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 GuessContentTypeFromFilename

func GuessContentTypeFromFilename(filename string) string

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

func UnmarshalHTTPRequest(into any, r *http.Request) error

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"`
}

func UnrestrictedCORS

func UnrestrictedCORS(handler http.Handler) http.Handler

UnrestrictedCORS wraps an HTTP handler with permissive CORS middleware that allows all origins, methods, headers, and credentials. This should only be used in development or when the API is intentionally public.

Types

type FormFieldUnmarshaler

type FormFieldUnmarshaler interface {
	UnmarshalFormField(value string) error
}

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

type HTTPClient struct {
	http.Client
	// contains filtered or unexported fields
}

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

type HTTPHeaderUnmarshaler interface {
	UnmarshalHTTPHeader(header string) error
}

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.

func (*MultipartPart) Read

func (mp *MultipartPart) Read(p []byte) (n int, err error)

Read implements io.Reader by delegating to the underlying Part's Read method.

type RouteParamUnmarshaler

type RouteParamUnmarshaler interface {
	UnmarshalRouteParam(param string) error
}

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

type URLPathUnmarshaler interface {
	UnmarshalURLPath(path string) error
}

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

type URLQueryUnmarshaler interface {
	UnmarshalURLQuery(values []string) error
}

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL