pureapi

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2025 License: Apache-2.0 Imports: 7 Imported by: 0

README

pureapi-core

Robust, type-safe HTTP APIs in Go with minimal boilerplate.

pureapi-core provides the essential building blocks for creating production-ready HTTP services. Whether you're building microservices, REST APIs, or web applications, this library gives you the power of modern Go patterns with a clean, intuitive API.

Key Features

  • Type-Safe Endpoints: Generic endpoint pipeline with compile-time type safety
  • Pluggable Architecture: Swap routers, query decoders, and middleware as needed
  • Zero Dependencies: Built on Go standard library only
  • Production Ready: Built-in body limits, panic recovery, and automatic HEAD/OPTIONS handling
  • Composable: Mix and match components to fit your architecture
  • Event-Driven: Built-in event emitter for observability and monitoring
  • Clean API: Express-like syntax with Go's type system benefits

Generic Endpoint Pipeline: Transform your HTTP handlers from error-prone manual parsing to type-safe, composable functions:

// Input → Logic → Error Handling → Output
handler := endpoint.NewHandler(
    inputJSON[UserRequest](),     // Parse JSON input
    businessLogic,                // Your typed business logic  
    errorMapper,                  // Map errors to HTTP responses
    outputJSON(),                 // Serialize JSON output
)

Smart Routing: Built-in router with path parameters, method validation, and automatic 405 responses.

Middleware Stack: Compose cross-cutting concerns like authentication, logging, and rate limiting.

Event System: Built-in event emitter for metrics, logging, and inter-service communication. Wire your own emitter with pureapi.WithEventEmitter to stream events into your observability stack.

Swappability: Pluggable architecture lets you swap components:

import (
    "github.com/aatuh/pureapi-core"
    brackets "github.com/aatuh/pureapi-querydec-brackets"
)

// Custom router and query decoder
server := pureapi.NewServer(
    pureapi.WithRouter(pureapi.NewBuiltinRouter()),
    pureapi.WithQueryDecoder(brackets.NewDecoder()),
)

server.Get("/users/:id", func(w http.ResponseWriter, r *http.Request) {
    // Access route params and query params
    params := pureapi.RouteParams(r)
    query := pureapi.QueryMap(r)
    
    // Handle request...
})

Install

go get github.com/aatuh/pureapi-core

Quick start

Check the examples from the examples package.

Run examples with:

go test -v -count 1 ./examples

# Run specific example.
go test -v -count 1 ./examples -run Test_BasicHTTP

Documentation

Overview

Package pureapi provides a unified API for building HTTP applications.

Package pureapi provides a unified API for building HTTP applications.

Example:

package main

import (
	"context"
	"fmt"
	"net/http"
	"log"

	"github.com/aatuh/pureapi-core"
)

func main() {
	// Create a new server
	server := pureapi.NewServer()

	// Register a simple GET route
	server.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("Hello, World!"))
	})

	// Register a route with parameters
	server.Get("/users/:id", func(w http.ResponseWriter, r *http.Request) {
		params := pureapi.RouteParams(r)
		userID := params["id"]

		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "User ID: %s", userID)
	})

	// Start the server
	log.Println("Server starting on :8080")
	if err := http.ListenAndServe(":8080", server.Handler()); err != nil {
		log.Fatal(err)
	}
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIErrorFrom

func APIErrorFrom(err APIError) *apierror.DefaultAPIError

APIErrorFrom converts an APIError to its default concrete type.

Parameters:

  • err: The API error to convert.

Returns:

  • *apierror.DefaultAPIError: The converted API error.

func NewAPIError

func NewAPIError(id string) *apierror.DefaultAPIError

NewAPIError constructs a new API error with an ID.

Parameters:

  • id: The error identifier.

Returns:

  • *apierror.DefaultAPIError: A new API error instance.

func NewBuiltinRouter

func NewBuiltinRouter() router.Router

NewBuiltinRouter exposes the tiny built-in router.

Returns:

  • router.Router: A new built-in router instance.

func NewHandler

func NewHandler[T any](
	ih InputHandler[T], lf HandlerLogicFn[T], eh ErrorHandler, oh OutputHandler,
) endpoint.Handler[T]

NewHandler constructs the default endpoint handler pipeline.

Parameters:

  • ih: The input handler for processing request input.
  • lf: The handler logic function for business logic.
  • eh: The error handler for mapping errors to API responses.
  • oh: The output handler for writing responses.

Returns:

  • endpoint.Handler[T]: A new handler instance.

func QueryMap

func QueryMap(r *http.Request) map[string]any

QueryMap exposes query parameters decoded into a map from request context.

Parameters:

  • r: The HTTP request.

Returns:

  • map[string]any: The decoded query parameters.

func RouteParams

func RouteParams(r *http.Request) map[string]string

RouteParams exposes route parameters extracted by the router.

Parameters:

  • r: The HTTP request.

Returns:

  • map[string]string: The extracted route parameters.

Types

type APIError

type APIError = apierror.APIError

APIError represents a structured API error.

type ErrorHandler

type ErrorHandler = endpoint.ErrorHandler

ErrorHandler maps errors to API errors and status codes.

type HandlerLogicFn

type HandlerLogicFn[T any] func(http.ResponseWriter, *http.Request, *T) (any, error)

HandlerLogicFn performs business logic for an endpoint.

type InputHandler

type InputHandler[T any] interface {
	endpoint.InputHandler[T]
}

InputHandler processes request input into a typed value.

type Middleware

type Middleware = endpoint.Middleware

Middleware wraps an http.Handler.

type Middlewares

type Middlewares = endpoint.Middlewares

Middlewares is a collection of middleware.

type OutputHandler

type OutputHandler = endpoint.OutputHandler

OutputHandler writes the response.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is a small facade over server.Handler with route helpers.

func NewServer

func NewServer(opts ...ServerOption) *Server

NewServer constructs a server with optional configuration.

Parameters:

  • opts: Optional server configuration options.

Returns:

  • *Server: A new Server instance with the specified configuration.

func (*Server) Delete

func (s *Server) Delete(path string, fn http.HandlerFunc) endpoint.Endpoint

Delete registers a DELETE route and returns the created endpoint for chaining.

Parameters:

  • path: The URL path for the route.
  • fn: The handler function for the route.

Returns:

  • endpoint.Endpoint: The created endpoint for method chaining.

func (*Server) Get

func (s *Server) Get(path string, fn http.HandlerFunc) endpoint.Endpoint

Get registers a GET route and returns the created endpoint for chaining.

Parameters:

  • path: The URL path for the route.
  • fn: The handler function for the route.

Returns:

  • endpoint.Endpoint: The created endpoint for method chaining.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the underlying http.Handler.

Returns:

  • http.Handler: The underlying HTTP handler.

func (*Server) Patch

func (s *Server) Patch(path string, fn http.HandlerFunc) endpoint.Endpoint

Patch registers a PATCH route and returns the created endpoint for chaining.

Parameters:

  • path: The URL path for the route.
  • fn: The handler function for the route.

Returns:

  • endpoint.Endpoint: The created endpoint for method chaining.

func (*Server) Post

func (s *Server) Post(path string, fn http.HandlerFunc) endpoint.Endpoint

Post registers a POST route and returns the created endpoint for chaining.

Parameters:

  • path: The URL path for the route.
  • fn: The handler function for the route.

Returns:

  • endpoint.Endpoint: The created endpoint for method chaining.

func (*Server) Put

func (s *Server) Put(path string, fn http.HandlerFunc) endpoint.Endpoint

Put registers a PUT route and returns the created endpoint for chaining.

Parameters:

  • path: The URL path for the route.
  • fn: The handler function for the route.

Returns:

  • endpoint.Endpoint: The created endpoint for method chaining.

type ServerOption

type ServerOption = server.HandlerOption

ServerOption configures the underlying HTTP handler.

func WithBodyLimit

func WithBodyLimit(limit int64) ServerOption

WithBodyLimit sets maximum request body size in bytes.

Parameters:

  • limit: The maximum request body size in bytes.

Returns:

  • ServerOption: A server option function.

func WithCustomNotFound

func WithCustomNotFound(h http.Handler) ServerOption

WithCustomNotFound sets a custom 404 handler.

Parameters:

  • h: The custom 404 handler.

Returns:

  • ServerOption: A server option function.

func WithEventEmitter

func WithEventEmitter(em event.EventEmitter) ServerOption

WithEventEmitter sets a custom event emitter for the server.

func WithQueryDecoder

func WithQueryDecoder(d querydec.Decoder) ServerOption

WithQueryDecoder sets the query decoder to use.

Parameters:

  • d: The query decoder to use.

Returns:

  • ServerOption: A server option function.

func WithRouter

func WithRouter(r router.Router) ServerOption

WithRouter sets the router to use.

Parameters:

  • r: The router implementation to use.

Returns:

  • ServerOption: A server option function.

type Stack

type Stack = endpoint.Stack

Stack manages an ordered list of wrappers.

func NewStack

func NewStack(wrappers ...Wrapper) Stack

NewStack creates a new middleware stack.

Parameters:

  • wrappers: The initial middleware wrappers.

Returns:

  • Stack: A new middleware stack.

type Wrapper

type Wrapper = endpoint.Wrapper

Wrapper wraps a middleware with an ID and optional metadata.

func NewWrapperFromHandler

func NewWrapperFromHandler(id string, mw func(http.Handler) http.Handler) Wrapper

NewWrapperFromHandler constructs a wrapper from an http middleware.

Parameters:

  • id: The identifier for the wrapper.
  • mw: The HTTP middleware function.

Returns:

  • Wrapper: A new middleware wrapper.

Directories

Path Synopsis
Package apierror provides structured error handling for HTTP APIs.
Package apierror provides structured error handling for HTTP APIs.
Package endpoint provides type-safe HTTP endpoint definitions and handlers.
Package endpoint provides type-safe HTTP endpoint definitions and handlers.
Package event provides an event-driven architecture for HTTP applications.
Package event provides an event-driven architecture for HTTP applications.
Package querydec provides flexible query parameter decoding for HTTP requests.
Package querydec provides flexible query parameter decoding for HTTP requests.
Package router provides pluggable HTTP routing with path parameter support.
Package router provides pluggable HTTP routing with path parameter support.
Package server provides HTTP server implementation with production features.
Package server provides HTTP server implementation with production features.

Jump to

Keyboard shortcuts

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