transwarp

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2026 License: MIT Imports: 5 Imported by: 0

README

Transwarp 🚀

alt text

Transwarp is a high-performance, abstraction layer for Go web servers. It allows you to write your HTTP logic using standard net/http handlers and run it on top of the industry's fastest web frameworks (Fiber, Echo, Gin, or Chi) without changing a single line of your business code.

Transwarp uses Go Build Tags to ensure zero overhead. If you compile for Gin, the Fiber dependencies are not included in your binary, and vice versa.

🌟 Key Features

  • Driver Agnostic: Switch between Fiber, Echo, Gin, and Chi just by changing a build flag.
  • Zero Overhead: Uses compile-time conditional inclusion. Your binary only contains the driver you select.
  • Standard Interface: Write standard http.HandlerFunc. No more proprietary c *gin.Context or c fiber.Ctx locking you in.
  • Unified Routing: Use universal :param syntax. Transwarp handles the translation to specific router syntaxes (e.g., {param} for Chi) automatically.
  • Middleware Bridging: Use standard func(next http.Handler) http.Handler middlewares. Transwarp adapts them to work correctly with Gin's Abort() or Fiber's middleware chain.
  • Mock Driver: Includes a thread-safe Mock Router for lightning-fast unit testing without opening TCP ports.

📦 Installation

$ go get github.com/profe-ajedrez/transwarp

⚡ Quick Start

1. Write your Application

Create a main.go. Note that you code against the transwarp interface, not the specific framework.

package main

import (
    "net/http"
    "github.com/profe-ajedrez/transwarp"
    // Import the package to trigger the build tags mechanism
    _ "github.com/profe-ajedrez/transwarp/internal/server/adapter/chiadapter"   // Optional reference
    _ "github.com/profe-ajedrez/transwarp/internal/server/adapter/echoadapterechoadapter"  // Optional reference
    _ "github.com/profe-ajedrez/transwarp/internal/server/adapter/fiberadapter" // Optional reference
    _ "github.com/profe-ajedrez/transwarp/internal/server/adapter/ginadapter"   // Optional reference
)

func main() {
    // 1. Get the driver instance (selected via build tags)
    server := transwarp.New()

    // 2. Register Routes
    server.GET("/hello/:name", func(w http.ResponseWriter, r *http.Request) {
        // Use Transwarp to extract params regardless of the underlying driver
        name := transwarp.Param(r, "name")
        w.Write([]byte("Hello, " + name))
    })

    // 3. Start
    server.Serve(":8080")
}
2. Build & Run

You decide which engine powers your app at compile time using -tags.

  • To use Fiber:
$ go build -tags fiber -o app main.go
$ ./app
  • To use Gin (Most Popular):
go build -tags gin -o app main.go
./app
  • To use Echo (v5):
go build -tags echo -o app main.go
./app
  • To use Chi (Lightweight):
go build -tags chi -o app main.go
./app

📚 API Documentation

1. Routing

Transwarp standardizes routing syntax. Always use :param for dynamic segments.

// Standard Verbs
server.GET("/users", handler)
server.POST("/users", handler)
server.PUT("/users/:id", handler)
server.DELETE("/users/:id", handler)

// Groups
api := server.Group("/api")
v1 := api.Group("/v1")
v1.GET("/status", statusHandler) // -> /api/v1/status
2. Accessing Parameters

Since http.Request doesn't natively support URL parameters, Transwarp injects them into the context. Use the helper function Param:

server.GET("/shop/category/:cat/item/:id", func(w http.ResponseWriter, r *http.Request) {
    // Works on Fiber, Gin, Echo, and Chi identically
    category := transwarp.Param(r, "cat")
    itemID   := transwarp.Param(r, "id")
    
    fmt.Fprintf(w, "Category: %s, Item: %s", category, itemID)
})
3. Middleware

Transwarp uses the standard "Onion" middleware pattern.

Important: If you want to stop the request chain (e.g., Auth failure), simply return without calling next.ServeHTTP. Transwarp ensures this translates correctly to the underlying engine (e.g., calling c.Abort() in Gin).

// Firewall Middleware
func AdminOnly(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        token := r.Header.Get("Authorization")
        
        if token != "secret-admin-token" {
            w.WriteHeader(http.StatusForbidden)
            w.Write([]byte("Access Denied"))
            // We return here. Transwarp ensures the next handler is NOT executed.
            return 
        }
        
        // Continue to the next handler
        next.ServeHTTP(w, r)
    })
}

// Usage
admin := server.Group("/admin")
admin.Use(AdminOnly)
admin.GET("/dashboard", dashboardHandler)
🛠 Supported Drivers
Driver	Build Tag	Description
Fiber	fiber	Uses Fiber v3. Built on fasthttp. Fastest option. Transwarp handles the complex context bridging automatically.
Echo	echo	Uses Echo v5. Robust and performant.
Gin	gin	Uses Gin Gonic. automatically sets ReleaseMode for production builds.
Chi	chi	Uses go-chi/chi v5. Native net/http compatibility.
🧪 Testing (The Mock Driver)

Transwarp includes a Thread-Safe Mock Router. This allows you to test your routing logic, middlewares, and handlers without spinning up a real TCP server or dealing with network latencies.

The Mock driver supports:

Route matching (including standard and dynamic routes).

Middleware execution.

Path parameter extraction.

Route collisions.
Example Test
func TestMyAPI(t *testing.T) {
    // 1. Create the Mock Router
    m := transwarp.NewMockRouter()
    
    // 2. Register your application routes
    m.GET("/api/user/:id", myHandler)
    
    // 3. Simulate a Request
    req := httptest.NewRequest("GET", "/api/user/42", nil)
    rec := httptest.NewRecorder()
    
    // 4. Execute directly (No network involved)
    // The Mock router automatically routes to 'myHandler' and injects "42" as param
    m.ServeHTTP(rec, req) 
    
    // 5. Assert
    if rec.Code != 200 {
        t.Errorf("Expected 200, got %d", rec.Code)
    }
}

⚠️ Advanced Notes

  • Fiber & Context

Fiber is based on fasthttp, which recycles request contexts for performance. Transwarp performs a deep copy of parameters and headers when bridging to net/http to ensure your handlers are safe to use, even if you perform asynchronous operations.

  • Gin & Abort

In Gin, simply returning from a middleware doesn't stop the chain; you must call Abort(). The Transwarp Gin Adapter detects if your standard middleware did not call next() and calls Abort() for you automatically.

📄 License

MIT License. See LICENSE for more information.

Documentation

Overview

Package transwarp provides a unified, framework-agnostic interface for HTTP routing in Go.

It acts as a wrapper layer that allows developers to write routing logic once and switch between different underlying web engines (such as Fiber, Gin, Echo, or Chi) at compile time using Go build tags.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Chain added in v1.0.1

func Chain(h http.HandlerFunc, mws ...Middleware) http.HandlerFunc

Chain is a helper that wraps a specific handler with a list of middlewares.

It allows applying middlewares to a single endpoint without creating a Group. The middlewares are applied in the order they are passed (first matches first).

Usage:

server.GET("/private", transwarp.Chain(myHandler, AuthMW, LoggingMW))

func Register

func Register(d Driver, c routerConstructor)

Register adds a driver constructor to the central registry.

This function is intended to be called within the `init()` functions of the driver-specific files (e.g., `driver_fiber.go`). This allows for a decoupled, plugin-like architecture where the core logic doesn't strictly depend on specific frameworks until they are explicitly linked by the compiler.

Parameters:

  • d: The Driver enum key (e.g., DriverFiber).
  • c: The constructor function that initializes that specific driver.

Types

type Config

type Config struct {
	// Driver specifies which underlying engine should be initialized.
	//
	// Important: The chosen Driver must match the build tags used during
	// compilation. For example, if DriverFiber is set, the application
	// must be built with `go build -tags fiber`.
	//
	// If the Driver does not match the compiled build tags, the Factory
	// method (New) will panic to prevent runtime inconsistencies.
	Driver Driver
}

Config holds the initialization settings for the Transwarp engine.

type Driver

type Driver string

Driver represents the specific web framework engine that Transwarp will use to handle HTTP requests.

The value of the Driver must match the build tag provided during compilation.

const (
	// DriverGin selects the Gin Gonic framework (v1).
	// To use this driver, you must compile with: -tags gin
	DriverGin Driver = "gin"

	// DriverEcho selects the Echo framework (v5).
	// To use this driver, you must compile with: -tags echo
	DriverEcho Driver = "echo"

	// DriverFiber selects the GoFiber framework (v3 Beta).
	// This driver offers high performance but requires specific handling for
	// zero-allocation contexts.
	// To use this driver, you must compile with: -tags fiber
	DriverFiber Driver = "fiber"

	// DriverChi selects the go-chi framework (v5).
	// This driver is fully compatible with standard net/http and is lightweight.
	// To use this driver, you must compile with: -tags chi
	DriverChi Driver = "chi"

	// DriverMock selects the internal Mock router.
	// This driver is intended for unit testing logic without spinning up
	// a real TCP network listener. It requires no specific build tags.
	DriverMock Driver = "mock"
)

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware defines the standard function signature for HTTP interceptors.

Transwarp enforces the standard "net/http" middleware pattern:

func(next http.Handler) http.Handler

This ensures that middlewares are portable and compatible across all supported drivers (Gin, Fiber, etc.), as Transwarp handles the necessary internal adaptations for non-standard frameworks.

type Transwarp

type Transwarp interface {
	internal.Router
}

Transwarp is the main interface that abstracts the routing logic.

It embeds the internal Router interface, exposing methods to:

  • Register routes (GET, POST, PUT, DELETE, etc.)
  • Create route groups with shared middleware.
  • Register middleware (Use).
  • Retrieve URL parameters in a unified way.
  • Start the HTTP server (Serve).

Implementation details are hidden behind this interface, allowing the underlying engine to be swapped without changing the consuming code.

func New

func New(cfg Config) Transwarp

New is the main factory method for instantiating the Transwarp engine.

It looks up the requested driver in the internal registry and returns an initialized Transwarp interface.

Panic: This function will panic if the requested Driver is not found in the registry. This usually happens when there is a mismatch between the code configuration and the compilation command.

Example of a Panic Scenario:

  • Code: transwarp.New(transwarp.Config{Driver: transwarp.DriverFiber})
  • Command: go run -tags gin main.go

In this case, the Fiber driver was never compiled, so it never registered itself, causing the lookup to fail. The command should has been:

  • Code: transwarp.New(transwarp.Config{Driver: transwarp.DriverFiber})
  • Command: go run .tags fiber main.go

Jump to

Keyboard shortcuts

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