httpsuite

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2024 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.

Note: Currently it only supports Chi.

Installation

To install httpsuite, run:

go get github.com/rluders/httpsuite

Usage

Request Parsing with URL Parameters

Easily parse incoming requests and set URL parameters:

package main

import (
	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"github.com/rluders/httpsuite"
	"log"
	"net/http"
)

type SampleRequest struct {
	Name string `json:"name" validate:"required,min=3"`
	Age  int    `json:"age" validate:"required,min=1"`
}

func (r *SampleRequest) SetParam(fieldName, value string) error {
	switch fieldName {
	case "name":
		r.Name = value
	}
	return nil
}

func main() {
	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)

	r.Post("/submit/{name}", func(w http.ResponseWriter, r *http.Request) {
		// Step 1: Parse the request and validate it
		req, err := httpsuite.ParseRequest[*SampleRequest](w, r, "name")
		if err != nil {
			log.Printf("Error parsing or validating request: %v", err)
			return
		}

		// Step 2: Send a success response
		httpsuite.SendResponse[SampleRequest](w, http.StatusOK, *req, nil, nil)
	})

	log.Println("Starting server on :8080")
	http.ListenAndServe(":8080", r)
}

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

This section is empty.

Variables

This section is empty.

Functions

func ParseRequest

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

ParseRequest parses the incoming HTTP request into a specified struct type, handling JSON decoding and URL parameters. It validates the parsed request and returns it along with any potential errors. The pathParams variadic argument allows specifying URL parameters to be extracted. If an error occurs during parsing, validation, or parameter setting, it responds with an appropriate HTTP status.

func SendResponse

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

SendResponse sends a JSON response to the client, using a unified structure for both success and error responses. T represents the type of the `data` payload. This function automatically adapts the response structure based on whether `data` or `errors` is provided, promoting a consistent API format.

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. Use `nil` for error responses.
  • errs: A slice of Error structs to describe issues. Use `nil` for successful responses.
  • meta: Optional metadata, such as pagination information. Use `nil` if not needed.

Types

type Error added in v1.0.1

type Error struct {
	// Code unique error code or HTTP status code for categorizing the error
	Code int `json:"code"`
	// Message user-friendly message describing the error.
	Message string `json:"message"`
	// Details additional details about the error, often used for validation errors.
	Details interface{} `json:"details,omitempty"`
}

Error represents an error in the aPI response, with a structured format to describe issues in a consistent manner.

type Meta added in v1.0.1

type Meta struct {
	// Page the current page number
	Page int `json:"page,omitempty"`
	// PageSize the number of items per page
	PageSize int `json:"page_size,omitempty"`
	// TotalPages the total number of pages available.
	TotalPages int `json:"total_pages,omitempty"`
	// TotalItems the total number of items across all pages.
	TotalItems int `json:"total_items,omitempty"`
}

Meta provides additional information about the response, such as pagination details. This is particularly useful for endpoints returning lists of data.

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"`
	Errors []Error `json:"errors,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 ValidationErrors

type ValidationErrors struct {
	Errors map[string][]string `json:"errors,omitempty"`
}

ValidationErrors represents a collection of validation errors for an HTTP request.

func IsRequestValid

func IsRequestValid(request any) *ValidationErrors

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

func NewValidationErrors

func NewValidationErrors(err error) *ValidationErrors

NewValidationErrors creates a new ValidationErrors instance from a given error. It extracts field-specific validation errors and maps them for structured output.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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