gate

package module
v0.3.0 Latest Latest
Warning

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

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

README

relicora-gate

relicora-gate is a lightweight Go library for building HTTP applications with a simple router, middleware support, and nested routers.

Current version: v0.2.0

Overview

The library provides:

  • App as the main HTTP application container
  • functional options for configuring address, port, and logger
  • Get, Post, Put, Delete methods to register routes
  • middleware support for both App and each Router
  • nested routers via App.NewRouter and Router.NewRouter
  • automatic 405 Method Not Allowed responses for wrong HTTP methods
  • a standalone middleware package for common middleware helpers

Installation

Run:

go get github.com/Relicora/relicora-gate

Then import the package in your Go code.

Quick Start

package main

import (
    "log"
    "net/http"

    "github.com/Relicora/relicora-gate"
)

func main() {
    app := gate.New(
        gate.WithPort(8080),
        gate.WithLogger(log.Default()),
    )

    app.AddMiddleware(func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            log.Printf("incoming request %s %s", r.Method, r.URL.Path)
            next.ServeHTTP(w, r)
        })
    })

    app.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello from relicora-gate"))
    })

    api := app.NewRouter("/api")
    api.Get("/ping", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("pong"))
    })

    log.Println("starting server")
    app.ListenAndServe()
}

Middleware package

The middleware package provides common middleware helpers for relicora-gate, including request logging with response duration.

Example:

package main

import (
    "log"
    "net/http"
    "time"

    "github.com/Relicora/relicora-gate"
    "github.com/Relicora/relicora-gate/middleware"
)

func main() {
    app := gate.New(
        gate.WithPort(8080),
        gate.WithLogger(log.Default()),
    )

    app.AddMiddleware(middleware.RequestLogger(log.Default()))
    app.AddMiddleware(middleware.Recoverer(log.Default()))
    app.AddMiddleware(middleware.Timeout(5 * time.Second))

    app.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello from relicora-gate"))
    })

    log.Println("starting server")
    app.ListenAndServe()
}

API Reference

gate.New(opts ...AppOption) *App

Creates a new App instance.

Supported options:

  • gate.WithAddr(addr string) sets the full server address, for example "127.0.0.1:8080"
  • gate.WithPort(port int) sets the server port; default address is :8080
  • gate.WithLogger(logger *log.Logger) sets a custom logger; if nil is passed, log.Default() is used
(*App) AddMiddleware(middleware func(http.Handler) http.Handler)

Adds middleware to the entire application. Middleware is executed in the order it is added.

(*App) Get/Post/Put/Delete(route string, handler func(http.ResponseWriter, *http.Request))

Registers a route on the main ServeMux.

(*App) NewRouter(prefix string) *Router

Creates a nested router mounted under the given prefix.

(*Router) NewRouter(prefix string) *Router

Creates a nested router under the current router.

(*Router) AddMiddleware(middleware func(http.Handler) http.Handler)

Adds middleware only for this specific router.

(*Router) Get/Post/Put/Delete(route string, handler func(http.ResponseWriter, *http.Request))

Registers a route inside a router. The route is defined without the parent prefix.

(*App) ListenAndServe()

Starts the HTTP server. To stop the server from tests or another context, use app.server.Close().

Nested Router Example

api := app.NewRouter("/api")
api.AddMiddleware(func(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("X-API", "true")
        next.ServeHTTP(w, r)
    })
})

v1 := api.NewRouter("/v1")
v1.Get("/status", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("ok"))
})

A request to /api/v1/status will be handled by the nested router and will also pass through the api middleware.

Wrong Method Handling

If a route is registered with Get, but the request uses POST, the library returns 405 Method Not Allowed.

Testing

Tests are located in gate_test.go.

Run them with:

go test ./...

Files and Recommendations

  • CHANGELOG.md contains the history of changes.
  • .gitignore includes coverage.out.

coverage.out is a temporary artifact produced by go test -coverprofile=coverage.out. It should not be committed to the repository.

Documentation

Overview

Package gate provides a lightweight HTTP application container with route registration, middleware support, and nested router handling.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type App

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

App represents the HTTP application and its route/middleware configuration.

func New

func New(opts ...AppOption) *App

New creates a new App with optional configuration options. The default server address is ":8080" unless overridden.

func (*App) AddMiddleware

func (a *App) AddMiddleware(middleware func(http.Handler) http.Handler)

AddMiddleware appends a middleware layer to the application. Middleware wraps request handling for all registered routes.

func (*App) Delete

func (a *App) Delete(route string, handler func(w http.ResponseWriter, r *http.Request))

Delete registers a handler for HTTP DELETE requests at the given route.

func (*App) Get

func (a *App) Get(route string, handler func(w http.ResponseWriter, r *http.Request))

Get registers a handler for HTTP GET requests at the given route.

func (*App) ListenAndServe

func (a *App) ListenAndServe() error

ListenAndServe applies registered middleware and starts the HTTP server. This method blocks until the server exits.

func (*App) NewRouter

func (a *App) NewRouter(prefix string) *Router

NewRouter creates a nested router mounted under the specified prefix. Requests beginning with the prefix are routed through the new Router.

func (*App) Post

func (a *App) Post(route string, handler func(w http.ResponseWriter, r *http.Request))

Post registers a handler for HTTP POST requests at the given route.

func (*App) Put

func (a *App) Put(route string, handler func(w http.ResponseWriter, r *http.Request))

Put registers a handler for HTTP PUT requests at the given route.

func (*App) Shutdown added in v0.3.0

func (a *App) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down.

type AppOption

type AppOption func(*App)

AppOption is a functional configuration option for an App.

func WithAddr

func WithAddr(addr string) AppOption

WithAddr sets the full address for the HTTP server. Example: "127.0.0.1:8080".

func WithLogger

func WithLogger(logger *log.Logger) AppOption

WithLogger sets a custom logger for application startup and request logging. If logger is nil, the default standard logger is preserved.

func WithPort

func WithPort(port int) AppOption

WithPort sets the port for the HTTP server. If WithAddr was also provided, the port is combined with the given host.

type Router

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

Router is a nested route container that supports its own middleware and routes.

func (*Router) AddMiddleware

func (r *Router) AddMiddleware(middleware func(http.Handler) http.Handler)

AddMiddleware adds middleware specifically for this router.

func (*Router) Delete

func (r *Router) Delete(route string, handler func(w http.ResponseWriter, r *http.Request))

Delete registers a handler for HTTP DELETE requests on this router.

func (*Router) Get

func (r *Router) Get(route string, handler func(w http.ResponseWriter, r *http.Request))

Get registers a handler for HTTP GET requests on this router.

func (*Router) NewRouter

func (r *Router) NewRouter(prefix string) *Router

NewRouter creates a child router under the current router prefix.

func (*Router) Post

func (r *Router) Post(route string, handler func(w http.ResponseWriter, r *http.Request))

Post registers a handler for HTTP POST requests on this router.

func (*Router) Put

func (r *Router) Put(route string, handler func(w http.ResponseWriter, r *http.Request))

Put registers a handler for HTTP PUT requests on this router.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP applies router middleware and delegates request handling to the router mux.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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