server

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 17 Imported by: 0

README

server

Gin-based HTTP server with h2c support, built-in middleware, health/info endpoints, and component lifecycle.

Install

go get github.com/kbukum/gokit/server@latest

Quick Start

import (
    "github.com/kbukum/gokit/server"
    "github.com/kbukum/gokit/logger"
)

log := logger.New()
srv := server.New(server.Config{Host: "0.0.0.0", Port: 8080}, log)
srv.ApplyDefaults("my-service", healthChecker)

srv.GinEngine().GET("/hello", func(c *gin.Context) {
    server.RespondOK(c, map[string]string{"msg": "hello"})
})

comp := server.NewComponent(srv)
comp.Start(ctx)
defer comp.Stop(ctx)

Key Types & Functions

Symbol Description
Server Wraps Gin engine + http.ServeMux with h2c
Config Host, Port, timeouts, max body size, CORS
ServerComponent Managed lifecycle — Start, Stop, Health
New(cfg, log) Create a server instance
(*Server) GinEngine() Access the underlying *gin.Engine
RespondOK(c, data) JSON 200 response
server/middleware
Function Description
Auth(AuthConfig) Token-based authentication
CORS(CORSConfig) Cross-origin resource sharing
Recovery() Panic recovery
server/endpoint
Function Description
Health(name, checker) /healthz endpoint
Info(name) /info build version endpoint

← Back to main gokit README

Documentation

Overview

Package server provides a unified HTTP server for gokit applications using Gin with HTTP/2 and h2c support for serving both REST and gRPC traffic.

The server follows gokit's component pattern with lifecycle management, health endpoints, and configurable middleware.

Middleware

Built-in middleware (server/middleware):

  • Recovery: Panic recovery with structured logging
  • Logging: Request/response logging with duration tracking
  • CORS: Cross-origin resource sharing configuration
  • RequestID: Request ID generation and propagation
  • RateLimit: Token bucket rate limiting
  • BodySize: Request body size limits
  • Auth: JWT authentication middleware

Endpoints

Built-in endpoints (server/endpoint):

  • /health: Health check aggregation
  • /info: Application information
  • /metrics: Prometheus metrics
  • /liveness: Kubernetes liveness probe
  • /readiness: Kubernetes readiness probe
  • /version: Build version information

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RespondAccepted

func RespondAccepted(c *gin.Context, data any)

RespondAccepted sends a 202 response wrapping data.

func RespondBadRequest

func RespondBadRequest(c *gin.Context, message string)

RespondBadRequest sends a 400 response with the given message.

func RespondCreated

func RespondCreated(c *gin.Context, data any)

RespondCreated sends a 201 response wrapping data.

func RespondForbidden

func RespondForbidden(c *gin.Context, message string)

RespondForbidden sends a 403 response.

func RespondInternalError

func RespondInternalError(c *gin.Context, cause error)

RespondInternalError sends a 500 response for the given cause.

func RespondNoContent

func RespondNoContent(c *gin.Context)

RespondNoContent sends a 204 with no body.

func RespondNotFound

func RespondNotFound(c *gin.Context, resource string)

RespondNotFound sends a 404 response for the given resource.

func RespondOK

func RespondOK(c *gin.Context, data any)

RespondOK sends a 200 response wrapping data.

func RespondOKWithMeta

func RespondOKWithMeta(c *gin.Context, data any, meta *Meta)

RespondOKWithMeta sends a 200 response with data and metadata.

func RespondUnauthorized

func RespondUnauthorized(c *gin.Context, message string)

RespondUnauthorized sends a 401 response.

func RespondWithError

func RespondWithError(c *gin.Context, err error)

RespondWithError inspects err: if it is an *apperrors.AppError the status and structured body are derived automatically; otherwise a generic 500 is sent.

Types

type Component

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

Component wraps Server to implement component.Component.

func NewComponent

func NewComponent(s *Server) *Component

NewComponent returns a component.Component backed by the given Server.

func (*Component) Describe

func (sc *Component) Describe() component.Description

Describe returns infrastructure summary info for the bootstrap display.

func (*Component) Health

func (sc *Component) Health(ctx context.Context) component.Health

Health returns the health status of the server.

func (*Component) Name

func (sc *Component) Name() string

Name returns the component name used for registration.

func (*Component) Routes

func (sc *Component) Routes() []component.Route

Routes returns all registered HTTP routes for the startup summary.

func (*Component) Start

func (sc *Component) Start(ctx context.Context) error

Start starts the underlying HTTP server.

func (*Component) Stop

func (sc *Component) Stop(ctx context.Context) error

Stop gracefully shuts down the underlying HTTP server.

type Config

type Config struct {
	Host         string                `yaml:"host" mapstructure:"host"`
	Port         int                   `yaml:"port" mapstructure:"port"`
	ReadTimeout  int                   `yaml:"read_timeout" mapstructure:"read_timeout"`   // seconds
	WriteTimeout int                   `yaml:"write_timeout" mapstructure:"write_timeout"` // seconds
	IdleTimeout  int                   `yaml:"idle_timeout" mapstructure:"idle_timeout"`   // seconds
	MaxBodySize  string                `yaml:"max_body_size" mapstructure:"max_body_size"` // e.g. "10MB"
	CORS         middleware.CORSConfig `yaml:"cors" mapstructure:"cors"`
	Enabled      bool                  `yaml:"enabled" mapstructure:"enabled"`
}

Config holds HTTP server configuration.

func (*Config) ApplyDefaults

func (c *Config) ApplyDefaults()

ApplyDefaults sets sensible default values for unset fields.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the configuration for invalid values.

type DataResponse

type DataResponse struct {
	Data any   `json:"data"`
	Meta *Meta `json:"meta,omitempty"`
}

DataResponse is the standard success envelope.

type Meta

type Meta struct {
	Page       int `json:"page,omitempty"`
	PageSize   int `json:"pageSize,omitempty"`
	Total      int `json:"total,omitempty"`
	TotalPages int `json:"totalPages,omitempty"`
}

Meta carries pagination or other response metadata.

type MountedHandler

type MountedHandler struct {
	Pattern string
	Label   string // optional human-readable label
}

MountedHandler records a handler mounted on the ServeMux.

type Server

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

Server is a unified HTTP server backed by Gin with optional support for additional http.Handler mounts (e.g. Connect-Go / gRPC) on the same port.

func New

func New(cfg *Config, log *logger.Logger) *Server

New creates a new Server. The Gin engine is created but no middleware is applied yet — call ApplyDefaults on the config first if needed.

func (*Server) Addr

func (s *Server) Addr() string

Addr returns the configured listen address.

func (*Server) ApplyDefaults

func (s *Server) ApplyDefaults(serviceName string, checker endpoint.HealthChecker)

ApplyDefaults applies the standard middleware stack and registers default endpoints.

func (*Server) ApplyMiddleware

func (s *Server) ApplyMiddleware()

ApplyMiddleware applies the standard middleware stack at the handler level so it covers ALL routes — both Gin REST endpoints and ConnectRPC services mounted via Handle().

func (*Server) GinEngine

func (s *Server) GinEngine() *gin.Engine

GinEngine returns the underlying Gin engine for route registration.

func (*Server) Handle

func (s *Server) Handle(pattern string, handler http.Handler)

Handle mounts an http.Handler at the given pattern on the root ServeMux. Use this to add Connect-Go or any other handler alongside Gin. The pattern must include a trailing slash for subtree matches (e.g. "/grpc.health.v1.Health/").

func (*Server) Handler

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

Handler returns the composed http.Handler (with middleware and h2c). Call ApplyMiddleware() first to ensure the middleware stack is applied. This is useful for testing with httptest.NewServer.

func (*Server) Mounts

func (s *Server) Mounts() []MountedHandler

Mounts returns all handlers mounted on the ServeMux (excluding Gin root).

func (*Server) RegisterDefaultEndpoints

func (s *Server) RegisterDefaultEndpoints(serviceName string, checker endpoint.HealthChecker)

RegisterDefaultEndpoints registers the standard /health, /info, and /metrics endpoints.

func (*Server) Start

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

Start binds the port and begins serving. It returns once the listener is bound so the caller knows the port is ready; serving continues in a goroutine.

func (*Server) Stop

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

Stop gracefully shuts down the server with a 5-second deadline.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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