Thanks to visit codestin.com
Credit goes to pkg.go.dev

restapi

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2025 License: MIT Imports: 16 Imported by: 0

README

Go Rest API Server

A lightweight helper package for building HTTP/HTTPS services with Gin. It provides sensible defaults, production‑friendly middleware, convenient response helpers, and support for listening on multiple interfaces and/or ports. It preserves backward compatibility with legacy single‑address APIs.

  • Multi‑address listeners for HTTP and HTTPS
  • Optional self‑signed TLS certificate generation for development
  • Minimal, composable middlewares: CORS, structured request logging, no‑cache headers
  • Small convenience helpers for consistent JSON responses
  • Tested, linted, and vulnerability‑checked in CI

Installation

Requirements: Go 1.25.3 or newer.

go get github.com/dan-sherwin/[email protected]

Quick Start

Single address (HTTP)
package main

import (
    "log"
    restapi "github.com/dan-sherwin/go-rest-api-server"
)

func main() {
    restapi.ListeningAddress = "0.0.0.0:5555"
    restapi.StartHttpServer()
    defer func() {
        if err := restapi.ShutdownHttpServer(); err != nil {
            log.Fatal(err)
        }
    }()

    select {} // serve forever
}
Multiple addresses (HTTP)
restapi.ListeningAddresses = []string{"0.0.0.0:8080", "127.0.0.1:9090"}
restapi.StartHttpServer()
HTTPS with self‑signed certificates (development)
// Start HTTPS on multiple addresses and auto‑generate a self‑signed cert/key.
restapi.HTTPSListeningAddresses = []string{"0.0.0.0:8443", "127.0.0.1:9443"}
restapi.StartHttpsServer("", "", true)
// Optionally ensure cleanup if your app may exit without calling Shutdown.
defer restapi.CleanupGeneratedTLSFiles()

API Overview

The package exposes a small set of globals and functions. Legacy names are preserved intentionally for backward compatibility.

  • Configuration
    • ListeningAddress string — default "0.0.0.0:5555"
    • HTTPSListeningAddress string — default "0.0.0.0:5556"
    • ListeningAddresses []string — if non‑empty, takes precedence over ListeningAddress
    • HTTPSListeningAddresses []string — if non‑empty, takes precedence over HTTPSListeningAddress
  • Server lifecycle
    • StartHttpServer() — start one or more HTTP servers
    • StartHttpsServer(certFile, keyFile string, autoSelfSigned bool) — start one or more HTTPS servers; when autoSelfSigned is true and cert/key are empty or missing, a dev self‑signed pair is generated and reused for all listeners
    • ShutdownHttpServer() error — graceful shutdown of all HTTP servers
    • ShutdownHttpsServer() error — graceful shutdown of all HTTPS servers and cleanup of any auto‑generated TLS files
    • CleanupGeneratedTLSFiles() — force cleanup of any auto‑generated TLS artifacts
  • Routing and utilities
    • RegisterRouters(funcs ...func(r *gin.Engine)) — add routes to the underlying Gin engine
    • DisablePing() — disables the default /ping route
    • ClientIP(c *gin.Context) string — returns X-Forwarded-For if present, otherwise c.ClientIP()

Middleware

In github.com/dan-sherwin/go-rest-api-server/middlewares:

  • CORSMiddleware() — permissive CORS headers with preflight handling
  • RequestLogger() — structured request logging (method, path, status, content length, referrer, UA, and body for non‑GET requests)
  • NoCache() — sets headers to prevent client/proxy caching

Use with your own Gin engine, or simply rely on the engine created by this package.

Response Helpers

In github.com/dan-sherwin/go-rest-api-server/restresponse:

  • RestSuccess(c *gin.Context, data any) — 200 JSON response
  • RestSuccessNoContent(c *gin.Context) — 204 response
  • Error helpers (map to sensible HTTP statuses):
    • RestErrorRespond(c, code, message, details...)
    • RestUnknownErrorRespond
    • RestBadRequestRespond
    • RestUnsupportedMediaTypeRespond
    • RestNotAcceptableRespond
    • RestPayloadTooLargeRespond
    • RestTooManyRequestsRespond
    • RestUnprocessableContentRespond

Status mapping is implemented via restresponse.HTTPStatusFromCode and restresponse.Code values.

Development

  • Run tests
    go test ./... -v
    
  • Lint
    golangci-lint run --timeout 5m
    
  • Security
    govulncheck ./...
    

Versioning & Changelog

This project follows Semantic Versioning. See CHANGELOG.md for release notes.

License

This project is licensed under the terms of the license found in the LICENSE file.

Documentation

Overview

Package restapi provides a lightweight HTTP/HTTPS server built on Gin with optional multi-address listening and helper utilities.

Index

Constants

This section is empty.

Variables

View Source
var (

	// Legacy single-address configuration (still supported)
	ListeningAddress      = "0.0.0.0:5555"
	HTTPSListeningAddress = "0.0.0.0:5556"

	// New: optional plural address config; if non-empty, takes precedence over the single address
	ListeningAddresses      []string
	HTTPSListeningAddresses []string
)

httpApp is the instance of the Gin Engine used for HTTP routing and handling.

httpServer represents the HTTP server that will serve requests over the network.

ListeningAddress is the address and port the server listens on for incoming HTTP connections.

Functions

func CleanupGeneratedTLSFiles added in v0.2.1

func CleanupGeneratedTLSFiles()

CleanupGeneratedTLSFiles removes any self-signed cert/key files generated by StartHttpsServer. Intended for applications to call (e.g., via defer) if they want to ensure cleanup even without calling ShutdownHttpsServer.

func ClientIP

func ClientIP(c *gin.Context) string

ClientIP retrieves the client IP address from the request context. It checks the "X-Forwarded-For" header first and returns its value if present; otherwise, it falls back to using c.ClientIP().

func DisablePing

func DisablePing()

DisablePing sets the internal `disablePing` variable to true, effectively disabling the ping functionality.

func RegisterRouters

func RegisterRouters(registrars ...func(r *gin.Engine))

RegisterRouters registers multiple router configurations to the HTTP application engine. It accepts a variadic number of functions, each receiving the *gin.Engine instance for adding routes and middleware.

func ShutdownHttpServer

func ShutdownHttpServer() error

ShutdownHttpServer gracefully shuts down all running HTTP servers. Returns the first error encountered (if any).

func ShutdownHttpsServer added in v0.2.1

func ShutdownHttpsServer() error

ShutdownHttpsServer gracefully shuts down all running HTTPS servers and cleans up any generated cert/key files. Returns the first error encountered (if any).

func StartHttpServer

func StartHttpServer()

StartHttpServer initializes and starts one or more HTTP servers at the configured listening addresses. If `ListeningAddresses` is non-empty, a server is started for each address; otherwise, the legacy single `ListeningAddress` is used. Servers run in separate goroutines for non-blocking operation.

func StartHttpsServer added in v0.2.1

func StartHttpsServer(certFile, keyFile string, autoSelfSigned bool)

StartHttpsServer initializes and starts one or more HTTPS servers with TLS using the provided certificate and key files. If `HTTPSListeningAddresses` is non-empty, a server is started for each address; otherwise, the legacy single `HTTPSListeningAddress` is used. Servers run asynchronously and log startup/errors.

Types

This section is empty.

Directories

Path Synopsis
Package middlewares contains Gin HTTP middlewares used by the restapi server (CORS, logging, no-cache).
Package middlewares contains Gin HTTP middlewares used by the restapi server (CORS, logging, no-cache).
Package restresponse defines response codes and helpers for consistent JSON API responses.
Package restresponse defines response codes and helpers for consistent JSON API responses.

Jump to

Keyboard shortcuts

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