servekit

package module
v0.4.4 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2026 License: MIT Imports: 6 Imported by: 0

README

servekit

A collection of reusable Go components for building HTTP and gRPC APIs. Designed to reduce boilerplate and provide consistent patterns across services.

Warning: Pre-v1.0.0 - expect breaking changes.

Go Reference

Install

go get github.com/marsolab/servekit

Requires Go 1.25+.

Quick Start

package main

import (
    "github.com/marsolab/servekit"
    "github.com/marsolab/servekit/httpkit"
    "github.com/marsolab/servekit/logkit"
)

func main() {
    logger := logkit.New(logkit.WithJSON())

    // Create a server that manages multiple listeners.
    srv := servekit.NewServer(logger)

    // Create an HTTP listener with built-in health checks and metrics.
    http := httpkit.NewListenerHTTP(":8080",
        httpkit.WithLogger(logger),
        httpkit.WithHealthCheck(),
        httpkit.WithMetrics(),
    )

    srv.RegisterListener("http", http)

    // Serve blocks until all listeners stop or the context is canceled.
    if err := srv.Serve(context.Background()); err != nil {
        logger.Error("server failed", slog.String("error", err.Error()))
        os.Exit(1)
    }
}

Architecture

The foundation is a Listener-based architecture:

  • Server orchestrates multiple listeners, runs them concurrently via errgroup, and handles graceful shutdown.
  • Listener is any component implementing Serve(ctx context.Context) error.
  • Built-in listeners: httpkit.ListenerHTTP and grpckit.ListenerGRPC.
  • Graceful shutdown propagates through context cancellation with configurable timeouts.

Configuration throughout the codebase uses the functional options pattern:

listener := httpkit.NewListenerHTTP(":8080",
    httpkit.WithLogger(logger),
    httpkit.WithHealthCheck(),
    httpkit.WithMetrics(),
    httpkit.WithCORS(corsOpts),
)

Packages

Core
Package Description
servekit (root) Server orchestrator - manages and runs multiple listeners concurrently
httpkit HTTP server built on chi with routing, middleware (logging, metrics, recovery, CORS), and standardized response helpers
httpkit/statuspage HTML status page template for health check endpoints
grpckit gRPC server with interceptor chains, graceful shutdown, and response utilities
Database
Package Description
dbkit/pgkit PostgreSQL via pgx/v5 with connection pooling and health checks
dbkit/pgkit/pgmigrate PostgreSQL migrations using tern
dbkit/litekit SQLite with Litestream backup support (S3 or file-based) and schema evolution
dbkit/chkit ClickHouse client via clickhouse-go
dbkit/mongokit MongoDB connections
dbkit/rediskit Redis client wrapper via go-redis

All database packages implement the hc.HealthChecker interface for health checks.

Authentication
Package Description
authkit/jwtkit JWT token signing, verification, and claims validation using cristalhq/jwt
authkit/hashkit Password hashing utilities
authkit/oauthkit OAuth provider integrations (Kinde)
Error Handling
Package Description
errkit Sentinel errors (ErrNotFound, ErrAlreadyExists, ErrUnauthenticated, etc.) with automatic HTTP status code mapping
errkit/sentrykit Sentry integration for error reporting
Utilities
Package Description
logkit Structured logging wrapper around log/slog with colored terminal output via tint
ctxkit Context management utilities including error logging hooks
idkit ULID generation using oklog/ulid and XID via rs/xid
retry Retry mechanisms with configurable backoff strategies
mailkit Email sending via Resend API
slackkit Slack notifications
tern Ternary operator helper

HTTP Middleware

httpkit provides composable middleware following chi's func(http.Handler) http.Handler pattern:

  • LoggingMiddleware - structured request/response logging
  • MetricsMiddleware - Prometheus metrics collection via VictoriaMetrics
  • RecoveryMiddleware - panic recovery with error reporting
  • CORSMiddleware - CORS configuration via go-chi/cors

Response Helpers

Standardized response functions for both HTTP and gRPC:

// HTTP responses.
httpkit.JSON(w, http.StatusOK, data)
httpkit.HTML(w, http.StatusOK, template, data)
httpkit.TEXT(w, http.StatusOK, "ok")
httpkit.ErrorHTTP(w, r, err) // maps errkit errors to HTTP status codes automatically

// gRPC responses.
grpckit.Error(err) // maps errkit errors to gRPC status codes

Health Checks

Components implement the hc.HealthChecker interface. The HTTP listener can expose a health endpoint aggregating checks from all registered services:

listener := httpkit.NewListenerHTTP(":8080",
    httpkit.WithHealthCheck(pgConn, redisConn, mongoConn),
)
// GET /health returns aggregated health status.

Testing

go test ./...

The project uses go-testdeep for assertions and table-driven tests throughout.

Contributing

See CONTRIBUTING.md for guidelines.

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error string

Error represents a package level error. Implements builtin error interface.

const (
	// ErrGracefullyShutdown represents an error message
	// indicating the failure to gracefully shut down a listener.
	ErrGracefullyShutdown Error = "shut down listener gracefully"

	// ErrCertPathRequired represents an error message
	// indicating that a certificate file path is required.
	ErrCertPathRequired Error = "certificate file path is required"

	// ErrPrivateKeyPathRequired represents an error message
	// indicating that a private key file path is required.
	ErrPrivateKeyPathRequired Error = "private key file path is required"
)

func (Error) Error

func (e Error) Error() string

Error returns the error message as a string. Implements the error interface.

type Listener

type Listener interface {
	// Serve runs the listener, handling incoming requests. It takes a context as an argument
	// and returns an error if an error occurs while serving requests.
	Serve(ctx context.Context) error
}

Listener is an interface that represents a listener which can serve requests. It requires the implementation of the Serve method that takes a context and returns an error.

type Server

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

Server is a type that represents a server that holds a map of listeners.

func NewServer

func NewServer(logger *slog.Logger) *Server

NewServer creates a new Server instance with an empty listeners map and returns a pointer to the created Server.

func (*Server) RegisterListener

func (s *Server) RegisterListener(name string, listener Listener)

RegisterListener adds a listener to the Server's listeners map.

func (*Server) Serve

func (s *Server) Serve(ctx context.Context) error

Serve runs the server and serves requests from all listeners. It creates an error group and a listener context. It iterates through the listeners map and starts a goroutine for each listener. Each goroutine retries calling the listener's Serve method until it succeeds or the retry limit is reached. If the Serve method returns an error, it logs an error message and checks if the error is retryable. If the context is canceled, it returns the context error. If the retry limit is reached, it returns ErrRetryLimitReached. Finally, it waits for all goroutines to complete and returns any error encountered during serving.

func (*Server) Shutdown

func (s *Server) Shutdown(timeout time.Duration) error

Shutdown gracefully shuts down all registered listeners within the given timeout.

Directories

Path Synopsis
authkit
dbkit
Package idkit provides the set of functions to generate different kind of identifiers.
Package idkit provides the set of functions to generate different kind of identifiers.

Jump to

Keyboard shortcuts

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