Categorygithub.com/nickbryan/httputil
modulepackage
0.0.0-20250217184512-07a1dd74159b
Repository: https://github.com/nickbryan/httputil.git
Documentation: pkg.go.dev

# README

httputil

Package httputil provides utility helpers for working with net/http adding sensible defaults, bootstrapping, and removing boilerplate code required to build web services.

Test Coverage Go Report Card License

Features

  • SerDe Handlers: Serialize/Deserialize request and response data with decreased boilerplate code.
    • NewJSONHandler provides encoding/decoding for JSON-based handlers.
  • Reduced Error Handling: Common error scenarios are handled and logged for consistency.
    • Server will attempt graceful shutdown and log errors appropriately.
  • Problem JSON Implementation: Standardized problem details for error responses as per RFC 9457.
    • Supports customization of problem payloads and proper JSON pointer handling for validation errors.
  • Middleware Support: Add common middleware such as panic recovery and logging with minimal effort.
  • Endpoint Management: Easily register and organise endpoints with prefixing and middleware chaining.

Quick Start

package main

import (
	"context"
	"net/http"

	"github.com/nickbryan/httputil"
	"github.com/nickbryan/slogutil"
)

func main() {
	logger := slogutil.NewJSONLogger()
	server := httputil.NewServer(logger)

	server.Register(
		httputil.EndpointsWithPrefix(
			"/api",
			httputil.EndpointsWithMiddleware(
				httputil.NewPanicRecoveryMiddleware(logger),
				newTestEndpoint(),
			)...,
		)...,
	)

	// GET http://localhost:8080/api/names
	server.Serve(context.Background())
}

func newTestEndpoint() httputil.Endpoint {
	return httputil.Endpoint{
		Method:  http.MethodGet,
		Path:    "/names",
		Handler: newTestHandler(),
	}
}

func newTestHandler() http.Handler {
	type response struct {
		Names []string `json:"names"`
	}

	return httputil.NewJSONHandler(func(r httputil.RequestNoBody) (*httputil.Response[response], error) {
		return httputil.NewResponse(http.StatusOK, response{Names: []string{"Dr Jones"}}), nil
	})
}

TODO

  • Implement the remaining problem details for common errors.
  • Review the docs for problem details to ensure they are correct and sufficient.
  • Update handler code to return the correct problem when they are all defined (empty body for example).
  • Update README to highlight problem json as a feature and provide examples of usage.
  • How do we allow people to return a custom error payload if required so they are not locked to problem json?
  • Document how errors take priority over responses, if an error is returned no response will be written if one is also returned.
  • Implement proper JSON pointer handling on validation errors as per https://datatracker.ietf.org/doc/html/rfc6901.
  • Test overwriting of base values in the problem json marshaling code.
  • Finish test existing code to achieve sensible coverage.
  • Decide on how to wrap logger, implement and test - use as is or clone the writeHandler so we can provide a static message and add the error as an attribute? Would also allow us to set pc?
  • Add common middleware.
  • Write the client side.
  • Check compatibility with Orchestrion.
  • Finalise all default values, ensure they are correct.
  • This README needs filling out properly.
  • Finalise all package documentation.

# Packages

Package problem provides utilities for constructing and handling error responses in accordance with RFC 9457 (Problem Details for HTTP APIs).

# Functions

Accepted creates a new Response object with a status code of http.StatusAccepted (202 Accepted) and the given data.
Created creates a new Response object with a status code of http.StatusCreated (201 Created) and the given data.
EndpointsWithMiddleware applies the given middleware to all provided endpoints.
EndpointsWithPrefix prefixes the given path to all provided endpoints.
NewJSONHandler creates a new http.Handler that wraps the provided [Handler] function to deserialize JSON request bodies and serialize JSON response bodies.
NewResponse creates a new Response object with the given status code and data.
NewServer creates a new Server instance with the specified logger and options.
NoContent creates a new Response object with a status code of http.StatusNoContent (204 No Content) and an empty struct as data.
OK creates a new Response with HTTP status code 200 (OK) containing the provided data.
Redirect creates a new Response object with the given status code and an empty struct as data.
WithAddress sets the address that the Server will listen and serve on.
WithIdleTimeout sets the idle timeout for the server.
WithReadHeaderTimeout sets the timeout for reading the request header.
WithReadTimeout sets the timeout for reading the request body.
WithShutdownTimeout sets the timeout for gracefully shutting down the server.
WithWriteTimeout sets the timeout for writing the response.

# Structs

Endpoint represents a registered HTTP endpoint.
No description provided by the author
No description provided by the author
Server is an HTTP server with graceful shutdown capabilities.

# Interfaces

No description provided by the author

# Type aliases

No description provided by the author
MiddlewareFunc defines a function type for HTTP middleware.
No description provided by the author