httpserver

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2026 License: MIT Imports: 9 Imported by: 0

README

httpserver

The httpserver package provides a Gin-based HTTP server with TLS, HTTP/2, configurable timeouts, trusted proxies, payload size limits, and graceful shutdown. It is intended for services that want a production-ready server setup without writing the same boilerplate in every project.

Import

import "github.com/raykavin/gobox/httpserver"

What it provides

  • NewGin() for creating a configured Gin engine
  • DefaultGinConfig() for a sensible starting configuration
  • Engine.SetupRoutes() and Engine.SetupMiddleware() for attaching routes and middleware
  • Engine.Listen() for starting the server (HTTP or HTTPS)
  • Engine.Shutdown() for graceful shutdown with a context deadline
  • TLS 1.2+ with curated cipher suites when UseSSL is true
  • HTTP/2 support when both UseSSL and EnableHTTP2 are true
  • automatic gin.Recovery() middleware when UseRecovery is true
  • configurable MaxPayloadSize enforced via http.MaxBytesReader

Main types

  • GinConfig: all server settings
  • Engine: wraps *gin.Engine and *http.Server with lifecycle methods
  • RouteSetup: func(*gin.Engine) passed to SetupRoutes
  • MiddlewareSetup: func(*gin.Engine) passed to SetupMiddleware

Example

package main

import (
    "context"
    "log"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"

    "github.com/gin-gonic/gin"
    "github.com/raykavin/gobox/httpserver"
)

func main() {
    cfg := httpserver.DefaultGinConfig()
    cfg.Port = 8080

    engine, err := httpserver.NewGin(cfg)
    if err != nil {
        log.Fatal(err)
    }

    engine.SetupRoutes(func(r *gin.Engine) {
        r.GET("/ping", func(c *gin.Context) {
            c.JSON(http.StatusOK, gin.H{"message": "pong"})
        })
    })

    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

    go func() {
        if err := engine.Listen(); err != nil && err != http.ErrServerClosed {
            log.Fatal(err)
        }
    }()
    log.Printf("listening on port %d", engine.GetPort())

    <-quit

    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    if err := engine.Shutdown(ctx); err != nil {
        log.Fatal(err)
    }
    log.Println("server stopped")
}

Default values

Field Default
Port 8080
ReadTimeout 15s
WriteTimeout 15s
IdleTimeout 60s
MinTLSVersion TLS 1.2
EnableHTTP2 true
UseRecovery true
NoRouteJSON true
MaxPayloadSize 10 MB

Errors

Sentinel Cause
ErrInvalidListenAddress Port is 0
ErrHostResolutionFailed Host is set but the address cannot be resolved
ErrInvalidSSLConfig UseSSL is true but SSLCert or SSLKey is empty
ErrServerNotInitialized Listen or Shutdown called before NewGin succeeded

Notes

  • HTTP/2 is only active when UseSSL is also true; plain HTTP/2 (h2c) is not supported
  • when NoRouteJSON is true, unmatched routes return a JSON 404 body instead of redirecting
  • set NoRouteTo to redirect unmatched routes to a fallback path (takes effect only when NoRouteJSON is false)
  • DebugMode: true sets Gin to debug mode and logs all registered routes on startup

Documentation

Overview

Package httpserver provides a Gin-based HTTP server with TLS, HTTP/2, configurable timeouts, trusted proxies, payload size limits, and graceful shutdown.

Basic usage

engine, err := httpserver.NewGin(httpserver.DefaultGinConfig())
if err != nil {
    log.Fatal(err)
}

engine.SetupRoutes(func(r *gin.Engine) {
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"message": "pong"})
    })
})

log.Fatal(engine.Listen())

Graceful shutdown

quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
go func() { log.Fatal(engine.Listen()) }()
<-quit

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = engine.Shutdown(ctx)

TLS

cfg := httpserver.DefaultGinConfig()
cfg.UseSSL  = true
cfg.SSLCert = "/etc/ssl/cert.pem"
cfg.SSLKey  = "/etc/ssl/key.pem"

engine, _ := httpserver.NewGin(cfg)
log.Fatal(engine.Listen())

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidListenAddress = errors.New("invalid listen address")
	ErrServerNotInitialized = errors.New("server not initialized")
	ErrInvalidSSLConfig     = errors.New("invalid SSL configuration")
	ErrHostResolutionFailed = errors.New("failed to resolve host address")
)

Functions

This section is empty.

Types

type Engine

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

Engine wraps Gin engine and implements HttpServer interface

func NewGin

func NewGin(config *GinConfig) (*Engine, error)

NewGin creates a new Gin engine with the provided configuration

func (*Engine) Addr

func (e *Engine) Addr() string

Addr returns the server address

func (Engine) GetPort

func (e Engine) GetPort() uint16

func (Engine) IsSSLEnabled

func (e Engine) IsSSLEnabled() bool

IsSSLEnabled returns whether SSL is enabled

func (*Engine) Listen

func (e *Engine) Listen() error

Listen starts the HTTP server

func (*Engine) ListenAndServeTLS

func (e *Engine) ListenAndServeTLS(certFile, keyFile string) error

ListenAndServeTLS starts the server with TLS

func (*Engine) Router

func (e *Engine) Router() *gin.Engine

Router provides access to the underlying Gin router

func (*Engine) Server

func (e *Engine) Server() *http.Server

Server provides access to the underlying HTTP server

func (*Engine) SetupMiddleware

func (e *Engine) SetupMiddleware(setup MiddlewareSetup)

SetupMiddleware applies middleware setup function to the router

func (*Engine) SetupRoutes

func (e *Engine) SetupRoutes(setup RouteSetup)

SetupRoutes applies route setup function to the router

func (*Engine) Shutdown

func (e *Engine) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server

func (*Engine) Use

func (e *Engine) Use(middleware ...gin.HandlerFunc)

Use adds middleware to the router

type GinConfig

type GinConfig struct {
	// Basic server config
	Host      string
	Port      uint16
	DebugMode bool

	// Timeouts
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
	IdleTimeout  time.Duration

	// SSL/TLS config
	UseSSL        bool
	SSLCert       string
	SSLKey        string
	MinTLSVersion uint16

	// HTTP/2 config
	EnableHTTP2 bool

	// Route handling
	NoRouteTo   string
	NoRouteJSON bool

	// Middleware config
	UseRecovery    bool
	TrustedProxies []string

	// Request limits
	MaxPayloadSize int64
}

GinConfig holds the configuration for creating a new Gin engine

func DefaultGinConfig

func DefaultGinConfig() *GinConfig

DefaultGinConfig returns a GinConfig with sensible defaults

type MiddlewareSetup

type MiddlewareSetup func(*gin.Engine)

MiddlewareSetup is a function type for setting up middleware

type RouteSetup

type RouteSetup func(*gin.Engine)

RouteSetup is a function type for setting up routes

Jump to

Keyboard shortcuts

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