httpsuite

package module
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2025 License: MIT Imports: 8 Imported by: 0

README

httpsuite

httpsuite is a Go library designed to simplify the handling of HTTP requests, validations, and responses in microservices. By providing a clear structure and modular approach, it helps developers write cleaner, more maintainable code with reduced boilerplate.

Features

  • Request Parsing: Streamline the parsing of incoming HTTP requests, including URL parameters.
  • Validation: Centralize validation logic for easy reuse and consistency.
  • Response Handling: Standardize responses across your microservices for a unified client experience.
  • Modular Design: Each component (Request, Validation, Response) can be used independently, enhancing testability and flexibility.
Supported routers
  • Gorilla MUX
  • Chi
  • Go Standard
  • ...maybe more? Submit a PR with an example.

Installation

To install httpsuite, run:

go get github.com/rluders/httpsuite/v2

Usage

Request Parsing with URL Parameters

Check out the example folder for a complete project demonstrating how to integrate httpsuite into your Go microservices.

Contributing

Contributions are welcome! Feel free to open issues, submit pull requests, and help improve httpsuite.

License

The MIT License (MIT). Please see License File for more information.

Documentation

Index

Constants

View Source
const BlankUrl = "about:blank"

Variables

This section is empty.

Functions

func GetProblemTypeURL added in v2.1.0

func GetProblemTypeURL(errorType string) string

GetProblemTypeURL get the full problem type URL based on the error type.

If the error type is not found in the predefined paths, it returns a default unknown error path.

Parameters: - errorType: The unique key identifying the error type (e.g., "validation_error").

Example usage:

problemTypeURL := GetProblemTypeURL("validation_error")

func ParseRequest

func ParseRequest[T RequestParamSetter](w http.ResponseWriter, r *http.Request, paramExtractor ParamExtractor, pathParams ...string) (T, error)

ParseRequest parses the incoming HTTP request into a specified struct type, handling JSON decoding and extracting URL parameters using the provided `paramExtractor` function. The `paramExtractor` allows flexibility to integrate with various routers (e.g., Chi, Echo, Gorilla Mux). It extracts the specified parameters from the URL and sets them on the struct.

The `pathParams` variadic argument is used to specify which URL parameters to extract and set on the struct.

The function also validates the parsed request. If the request fails validation or if any error occurs during JSON parsing or parameter extraction, it responds with an appropriate HTTP status and error message.

Parameters:

  • `w`: The `http.ResponseWriter` used to send the response to the client.
  • `r`: The incoming HTTP request to be parsed.
  • `paramExtractor`: A function that extracts URL parameters from the request. This function allows custom handling of parameters based on the router being used.
  • `pathParams`: A variadic argument specifying which URL parameters to extract and set on the struct.

Returns:

  • A parsed struct of the specified type `T`, if successful.
  • An error, if parsing, validation, or parameter extraction fails.

Example usage:

request, err := ParseRequest[MyRequestType](w, r, MyParamExtractor, "id", "name")
if err != nil {
    // Handle error
}

// Continue processing the valid request...

func SendResponse

func SendResponse[T any](w http.ResponseWriter, code int, data T, problem *ProblemDetails, meta *Meta)

SendResponse sends a JSON response to the client, supporting both success and error scenarios.

Parameters:

  • w: The http.ResponseWriter to send the response.
  • code: HTTP status code to indicate success or failure.
  • data: The main payload of the response (only for successful responses).
  • problem: An optional ProblemDetails struct (used for error responses).
  • meta: Optional metadata for successful responses (e.g., pagination details).

func SetProblemBaseURL added in v2.1.0

func SetProblemBaseURL(baseURL string)

SetProblemBaseURL configures the base URL used in the "type" field for ProblemDetails.

This function allows applications using httpsuite to provide a custom domain and structure for error documentation URLs. By setting this base URL, the library can generate meaningful and discoverable problem types.

Parameters: - baseURL: The base URL where error documentation is hosted (e.g., "https://api.mycompany.com").

Example usage:

httpsuite.SetProblemBaseURL("https://api.mycompany.com")

Once configured, generated ProblemDetails will include a "type" such as:

"https://api.mycompany.com/errors/validation-error"

If the base URL is not set, the default value for the "type" field will be "about:blank".

func SetProblemErrorTypePath added in v2.1.0

func SetProblemErrorTypePath(errorType, path string)

SetProblemErrorTypePath sets or updates the path for a specific error type.

This allows applications to define custom paths for error documentation.

Parameters: - errorType: The unique key identifying the error type (e.g., "validation_error"). - path: The path under the base URL where the error documentation is located.

Example usage:

httpsuite.SetProblemErrorTypePath("validation_error", "/errors/validation-error")

After setting this path, the generated problem type for "validation_error" will be:

"https://api.mycompany.com/errors/validation-error"

func SetProblemErrorTypePaths added in v2.1.0

func SetProblemErrorTypePaths(paths map[string]string)

SetProblemErrorTypePaths sets or updates multiple paths for different error types.

This allows applications to define multiple custom paths at once.

Parameters: - paths: A map of error types to paths (e.g., {"validation_error": "/errors/validation-error"}).

Example usage:

paths := map[string]string{
    "validation_error":  "/errors/validation-error",
    "not_found_error":   "/errors/not-found",
}
httpsuite.SetProblemErrorTypePaths(paths)

This method overwrites any existing paths with the same keys.

Types

type Meta

type Meta struct {
	Page       int `json:"page,omitempty"`
	PageSize   int `json:"page_size,omitempty"`
	TotalPages int `json:"total_pages,omitempty"`
	TotalItems int `json:"total_items,omitempty"`
}

Meta provides additional information about the response, such as pagination details.

type ParamExtractor

type ParamExtractor func(r *http.Request, key string) string

ParamExtractor is a function type that extracts a URL parameter from the incoming HTTP request. It takes the `http.Request` and a `key` as arguments, and returns the value of the URL parameter as a string. This function allows flexibility for extracting parameters from different routers, such as Chi, Echo, Gorilla Mux, or the default Go router.

Example usage:

paramExtractor := func(r *http.Request, key string) string {
    return r.URL.Query().Get(key)
}

type ProblemDetails added in v2.1.0

type ProblemDetails struct {
	Type       string                 `json:"type"`                 // A URI reference identifying the problem type.
	Title      string                 `json:"title"`                // A short, human-readable summary of the problem.
	Status     int                    `json:"status"`               // The HTTP status code.
	Detail     string                 `json:"detail,omitempty"`     // Detailed explanation of the problem.
	Instance   string                 `json:"instance,omitempty"`   // A URI reference identifying the specific instance of the problem.
	Extensions map[string]interface{} `json:"extensions,omitempty"` // Custom fields for additional details.
}

ProblemDetails conforms to RFC 9457, providing a standard format for describing errors in HTTP APIs.

func IsRequestValid

func IsRequestValid(request any) *ProblemDetails

IsRequestValid validates the provided request struct using the go-playground/validator package. It returns a ProblemDetails instance if validation fails, or nil if the request is valid.

func NewProblemDetails added in v2.1.0

func NewProblemDetails(status int, problemType, title, detail string) *ProblemDetails

NewProblemDetails creates a ProblemDetails instance with standard fields.

func NewValidationProblemDetails added in v2.1.0

func NewValidationProblemDetails(err error) *ProblemDetails

NewValidationProblemDetails creates a ProblemDetails instance based on validation errors. It maps field-specific validation errors into structured details.

type RequestParamSetter

type RequestParamSetter interface {
	// SetParam assigns a value to a specified field in the request struct.
	// The fieldName parameter is the name of the field, and value is the value to set.
	SetParam(fieldName, value string) error
}

RequestParamSetter defines the interface used to set the parameters to the HTTP request object by the request parser. Implementing this interface allows custom handling of URL parameters.

type Response

type Response[T any] struct {
	Data T     `json:"data,omitempty"`
	Meta *Meta `json:"meta,omitempty"`
}

Response represents the structure of an HTTP response, including a status code, message, and optional body. T represents the type of the `Data` field, allowing this structure to be used flexibly across different endpoints.

type ValidationErrorDetail added in v2.1.0

type ValidationErrorDetail struct {
	Field   string `json:"field"`   // The name of the field that failed validation.
	Message string `json:"message"` // A human-readable message describing the error.
}

ValidationErrorDetail provides structured details about a single validation error.

Jump to

Keyboard shortcuts

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