velocity

package module
v1.0.1-alpha Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2024 License: MIT Imports: 10 Imported by: 0

README

Velocity

A high-performance "Express-like" HTTP router for Go with radix trie-based routing, middleware support, and WebSocket capabilities.

Go Reference Go Report Card License

Features
  • Fast radix tree routing
  • Path parameters (/users/:id)
  • Middleware support (global and per-route)
  • Automatic HEAD and OPTIONS handling
  • WebSocket support
  • HTTP/2 support with TLS
  • Route groups
  • Custom 404 and 405 handlers
  • Built-in middleware suite

Table of Contents

Installation

go get github.com/Juanfec4/velocity
Requirements
  • Go 1.21 or higher
  • HTTP/2 support requires TLS configuration

Quick Start

package main

import (
    "github.com/Juanfec4/velocity"
    "github.com/Juanfec4/velocity/middleware"
    "net/http"
)

func main() {
    app := velocity.New()
    router := app.Router("/api",
        middleware.Logger(),
        middleware.CORS(),
        middleware.RequestID(),
    )

    router.Get("/users/:id").Handle(func(w http.ResponseWriter, r *http.Request) {
        params := velocity.GetParams(r)
        userID := params["id"]
        // Handle request
    })

    app.Listen(8080)
}

Routing

Basic Routes
router.Get("/users").Handle(handler)
router.Post("/users").Handle(handler)
router.Put("/users/:id").Handle(handler)
router.Patch("/users/:id").Handle(handler)
router.Delete("/users/:id").Handle(handler)
router.Websocket("/chat").Handle(handler)
Route Groups
// Create a group with a path prefix
api := router.Group("/v1")

// Add middleware to group
authorized := api.Group("/admin", authMiddleware)

api.Get("/public").Handle(publicHandler)
authorized.Get("/private").Handle(privateHandler)
Path Parameters
router.Get("/users/:id").Handle(func(w http.ResponseWriter, r *http.Request) {
    params := velocity.GetParams(r)
    userID := params["id"]
    // Use parameter
})

Route Validation Rules

  • Path parameters must be alphanumeric with underscores (e.g., :userId, :user_id)
  • Catch-all routes (*) must be the final segment
  • Cannot have consecutive parameters (e.g., /users/:id/:name)
  • Parameter names must be unique within a route

Automatic Method Handling

HEAD Requests

When a GET route is registered, HEAD requests to that route are automatically handled. The response includes the same headers as the GET request would return, but with no body.

OPTIONS Requests

OPTIONS requests are automatically handled with appropriate CORS headers based on your configuration. The response includes:

  • Access-Control-Allow-Methods: Lists all methods allowed for the route
  • Access-Control-Allow-Headers: Lists all headers allowed
  • Access-Control-Allow-Origin: Based on CORS configuration
  • Access-Control-Expose-Headers: Lists exposed headers if configured

Custom Error Handlers

app.NotFound(func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusNotFound)
    w.Write([]byte("Custom 404"))
})

app.NotAllowed(func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusMethodNotAllowed)
    w.Write([]byte("Custom 405"))
})

Server Configuration

app.Listen(443, velocity.ServerConfig{
    CertFile: "cert.pem",
    KeyFile: "key.pem",
    ReadTimeout: 5 * time.Second,
    WriteTimeout: 10 * time.Second,
    IdleTimeout: 120 * time.Second,
})

Built-in Middleware

Logger

Logs HTTP request details with customizable format and colors.

Configuration options:

  • Format: Log format string (default: "[%s] %s %s %s %s %v")
  • Skip: Paths to skip logging (default: [])
  • Logger: Custom logger instance (default: log.Default())
  • Colors: Enable colored output (default: auto-detected)
router := app.Router("/api", middleware.Logger(middleware.LoggerConfig{
    Colors: &true,
    Skip: &[]string{"/health"},
    Format: &"[%s] %s %s %s %s %v",
    Logger: customLogger,
}))
CORS

Handles Cross-Origin Resource Sharing (CORS) headers.

Configuration options:

  • AllowedMethods: Allowed HTTP methods (default: ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD"])
  • AllowedHeaders: Allowed HTTP headers (default: ["Accept", "Content-Type", "Content-Length", "Accept-Encoding", "Authorization"])
  • ExposedHeaders: Headers exposed to the client (default: [])
  • AllowedOrigins: Allowed origins (default: ["*"])
router := app.Router("/api", middleware.CORS(middleware.CorsConfig{
    AllowedOrigins: &[]string{"https://example.com"},
    AllowedMethods: &[]string{"GET", "POST", "PUT"},
    AllowedHeaders: &[]string{"Content-Type", "Authorization"},
    ExposedHeaders: &[]string{"X-Request-ID"},
}))
Request ID

Adds unique request ID tracking using UUID v4 by default.

Configuration options:

  • Header: Header for request ID (default: "X-Request-ID")
  • Generator: Custom ID generator function (default: uuid.New().String)
router := app.Router("/api", middleware.RequestID(middleware.RequestIDConfig{
    Header: &"X-Correlation-ID",
    Generator: func() string {
        return "custom-id"
    },
}))

// Get request ID in handler
requestID := middleware.GetRequestID(r)
Client IP

Extracts and verifies client IP addresses.

Configuration options:

  • Header: Header to check for client IP (default: "X-Real-IP")
  • TrustProxy: Enable proxy headers (default: true)
router := app.Router("/api", middleware.ClientIP(middleware.ClientIPConfig{
    Header: &"X-Real-IP",
    TrustProxy: &true,
}))

// Get client IP in handler
clientIP := middleware.GetClientIP(r)
Error Recovery

Recovers from panics in request handlers.

Configuration options:

  • Cb: Callback function called on panic (default: logs to stderr)
router := app.Router("/api", middleware.ErrRecover(middleware.ErrRecoverConfig{
    Cb: func(v any) {
        log.Printf("Recovered from panic: %v", v)
    },
}))

Contributing

We welcome contributions to Velocity! Here's how you can help:

Getting Started
  1. Fork the repository
  2. Create a new branch for your feature (git checkout -b feature/amazing-feature)
  3. Write tests for your changes
  4. Implement your changes
  5. Run tests (go test ./...) and ensure they pass
  6. Update documentation as needed
  7. Commit your changes (git commit -m 'Add amazing feature')
  8. Push to your branch (git push origin feature/amazing-feature)
  9. Open a Pull Request
Development Guidelines
  • Follow Go best practices and style guide
  • Write tests for new features
  • Update documentation for API changes
  • Keep commits focused and atomic
  • Use meaningful commit messages
Issues and Discussions
  • Check existing issues before creating new ones
  • Use issue templates when reporting bugs
  • Be specific about problems and steps to reproduce
  • Engage respectfully in discussions

Documentation

Overview

Package velocity is a high-performance HTTP router and web framework for Go. It features flexible routing, middleware support, and automatic handling of OPTIONS/WebSocket requests.

Basic Usage:

app := velocity.New()
router := app.Router("/api")

// Add a route
router.Get("/users/:id").Handle(func(w http.ResponseWriter, r *http.Request) {
    params := velocity.GetParams(r)
    userID := params["id"]
    // ... handle request
})

// Start server
app.Listen(8080)

Groups and Middleware:

// Create a group with middleware
authMiddleware := func(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // ... auth logic
        next(w, r)
    }
}

api := router.Group("/v1", authMiddleware)
api.Get("/protected").Handle(handler)

Configuration:

// Configure app options
app := velocity.New(velocity.AppConfig{
    AllowTrace: true,
})

// Configure server with TLS
app.Listen(443, velocity.ServerConfig{
    CertFile: "cert.pem",
    KeyFile:  "key.pem",
})

Available HTTP Methods:

  • GET (also handles HEAD requests)
  • POST
  • PUT
  • PATCH
  • DELETE
  • WebSocket (automatic upgrade detection)
  • OPTIONS (automatic handling)

Features:

  • Fast routing with radix tree
  • Path parameters (/users/:id)
  • Middleware support (global and per-route)
  • Automatic HEAD and OPTIONS handling
  • WebSocket support
  • HTTP/2 support with TLS
  • Custom 404 and 405 handlers

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetParams

func GetParams(r *http.Request) map[string]string

GetParams retrieves URL parameters from the request context.

Example:

router.Get("/users/:id").Handle(func(w http.ResponseWriter, r *http.Request) {
    params := velocity.GetParams(r)
    userID := params["id"]
})

Types

type App

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

App is the main router instance that implements http.Handler.

func New

func New(cfg ...AppConfig) *App

New creates a new App instance with optional configuration.

Example:

app := velocity.New()
// or with config
app := velocity.New(velocity.AppConfig{AllowTrace: true})

func (*App) Listen

func (a *App) Listen(port int, cfg ...ServerConfig) error

Listen starts the HTTP server on the specified port with optional configuration. The server will use the following defaults if not specified:

  • ReadTimeout: 0 (no timeout)
  • WriteTimeout: 0 (no timeout)
  • IdleTimeout: 0 (no timeout)

Example:

// Basic usage
app.Listen(8080)

// With timeouts
app.Listen(8080, ServerConfig{
    ReadTimeout: 5 * time.Second,
    WriteTimeout: 10 * time.Second,
    IdleTimeout: 120 * time.Second,
})

// With TLS
app.Listen(443, ServerConfig{
    CertFile: "cert.pem",
    KeyFile: "key.pem",
    ReadTimeout: 5 * time.Second,
    WriteTimeout: 10 * time.Second,
    IdleTimeout: 120 * time.Second,
})

func (*App) NotAllowed

func (a *App) NotAllowed(h http.HandlerFunc)

NotAllowed sets a custom handler for method not allowed responses (405).

func (*App) NotFound

func (a *App) NotFound(h http.HandlerFunc)

NotFound sets a custom handler for not found responses (404).

func (*App) Router

func (a *App) Router(path string, mws ...Middleware) *Router

Router creates a new router group with the given path prefix and optional middleware.

Example:

router := app.Router("/api", authMiddleware)

func (*App) Routes

func (a *App) Routes(print ...bool) []string

Routes returns all registered routes. If print is true, routes are also printed to stdout.

func (*App) ServeHTTP

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

type AppConfig

type AppConfig struct {
	// AllowTrace enables automatic handling of TRACE requests
	AllowTrace bool
}

AppConfig holds configuration options for the App.

type Middleware

type Middleware func(next http.HandlerFunc) http.HandlerFunc

Middleware represents a function that wraps an http.HandlerFunc to provide additional functionality before and/or after the handler execution.

type Router

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

Router represents a group of routes with a common path prefix and middleware.

func (*Router) Delete

func (r *Router) Delete(p string, mws ...Middleware) route

Delete registers a new DELETE route with the given path and optional middleware.

func (*Router) Get

func (r *Router) Get(p string, mws ...Middleware) route

Get registers a new GET route with the given path and optional middleware.

func (*Router) Group

func (r *Router) Group(path string, mws ...Middleware) *Router

Group creates a new router group with additional path prefix and optional middleware.

Example:

api := router.Group("/v1", authMiddleware)

func (*Router) Patch

func (r *Router) Patch(p string, mws ...Middleware) route

Patch registers a new PATCH route with the given path and optional middleware.

func (*Router) Post

func (r *Router) Post(p string, mws ...Middleware) route

Post registers a new POST route with the given path and optional middleware.

func (*Router) Put

func (r *Router) Put(p string, mws ...Middleware) route

Put registers a new PUT route with the given path and optional middleware.

func (*Router) Websocket

func (r *Router) Websocket(p string, mws ...Middleware) route

Websocket registers a new WebSocket route with the given path and optional middleware.

type ServerConfig

type ServerConfig struct {
	// Addr specifies the TCP address for the server to listen on
	Addr string

	// TLSConfig provides configuration for TLS connections
	TLSConfig *tls.Config

	// CertFile and KeyFile are paths to TLS certificate and key files
	CertFile string
	KeyFile  string

	// ReadTimeout is the maximum duration for reading the entire request, including the body.
	// A zero or negative value means there will be no timeout.
	// Default: 0 (no timeout)
	ReadTimeout time.Duration

	// WriteTimeout is the maximum duration before timing out writes of the response.
	// A zero or negative value means there will be no timeout.
	// Default: 0 (no timeout)
	WriteTimeout time.Duration

	// IdleTimeout is the maximum amount of time to wait for the next request.
	// If IdleTimeout is zero, the value of ReadTimeout is used.
	// If both are zero, there is no timeout.
	// Default: 0 (no timeout)
	IdleTimeout time.Duration
}

ServerConfig provides TLS and server address configuration.

Directories

Path Synopsis
examples
Package middleware provides common HTTP middleware functions for the velocity router.
Package middleware provides common HTTP middleware functions for the velocity router.

Jump to

Keyboard shortcuts

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