Categorygithub.com/goliatone/go-router
modulepackage
0.1.0
Repository: https://github.com/goliatone/go-router.git
Documentation: pkg.go.dev

# README

go-router

A lightweight, generic HTTP router interface for Go that enables framework-agnostic HTTP handling with built-in adapters. This package provides an abstraction for routing, making it easy to switch between different HTTP router implementations.

Installation

go get github.com/goliatone/go-router

Overview

go-router provides a common interface for HTTP routing that can be implemented by different HTTP frameworks. Currently includes a Fiber and HTTPRouter with plans to support more frameworks.

Usage

Basic Example with Fiber

package main

import (
    "github.com/goliatone/go-router"
    "github.com/gofiber/fiber/v2"
)

func main() {
    // Create new Fiber adapter
    app := router.NewFiberAdapter()

    // Add middleware
    app.Router().Use(func(c router.Context) error {
        c.SetHeader("Content-Type", "application/json")
        return c.Next()
    })

    // Add routes
    app.Router().Get("/hello", func(c router.Context) error {
        return c.JSON(200, map[string]string{"message": "Hello World!"})
    })

    // Start server
    app.Serve(":3000")
}

Route Groups

api := app.Router().Group("/api")
{
    api.Post("/users", createUser(store)).Name("user.create")
    api.Get("/users", listUsers(store)).Name("user.list")
    api.Get("/users/:id", getUser(store)).Name("user.get")
    api.Put("/users/:id", updateUser(store)).Name("user.update")
    api.Delete("/users/:id", deleteUser(store)).Name("user.delete")
}

Builder

api := app.Router().Group("/api")

builder := router.NewRouteBuilder(api)

users := builder.Group("/users")
{
    users.NewRoute().
        POST().
        Path("/").
        Description("Create a new user").
        Tags("User").
        Handler(createUser(store)).
        Name("user.create")

    users.NewRoute().
        GET().
        Path("/").
        Description("List all users").
        Tags("User").
        Handler(listUsers(store)).
        Name("user.list")

    users.NewRoute().
        GET().
        Path("/:id").
        Description("Get user by ID").
        Tags("User").
        Handler(getUser(store)).
        Name("user.get")

    users.NewRoute().
        PUT().
        Path("/:id").
        Description("Update user by ID").
        Tags("User").
        Handler(updateUser(store)).
        Name("user.update")

    users.NewRoute().
        DELETE().
        Path("/:id").
        Description("Delete user by ID").
        Tags("User").
        Handler(deleteUser(store)).
        Name("user.delete")

    users.BuildAll()
}

API Reference

Server Interface

type Server[T any] interface {
    Router() Router[T]
    WrapHandler(HandlerFunc) any
    WrappedRouter() T
    Serve(address string) error
    Shutdown(ctx context.Context) error
}

Router Interface

type Router[T any] interface {
    Handle(method HTTPMethod, path string, handler ...HandlerFunc) RouteInfo
    Group(prefix string) Router[T]
    Use(args ...any) Router[T]
    Get(path string, handler HandlerFunc) RouteInfo
    Post(path string, handler HandlerFunc) RouteInfo
    Put(path string, handler HandlerFunc) RouteInfo
    Delete(path string, handler HandlerFunc) RouteInfo
    Patch(path string, handler HandlerFunc) RouteInfo
}

Context Interface

type Context interface {
    Method() string
    Path() string
    Param(name string) string
    Query(name string) string
    Queries() map[string]string
    Status(code int) Context
    Send(body []byte) error
    JSON(code int, v any) error
    NoContent(code int) error
    Bind(any) error
    Context() context.Context
    SetContext(context.Context)
    Header(string) string
    SetHeader(string, string)
    Next() error
}

License

MIT

# Packages

No description provided by the author
No description provided by the author

# Functions

DefaultErrorHandlerConfig provides sensible defaults.
No description provided by the author
No description provided by the author
No description provided by the author
ExtractSchemaFromType generates SchemaMetadata from a Go type using reflection.
GetContextValue functions for type assertion.
InitializeViewEngine will initialize a view engine with default values.
LogError logs the error with context information.
MapToRouterError converts any error to RouterError.
MiddlewareFromFiber adapts a user-provided Fiber middleware to your router's chain, preserving c.Next() semantics by spinning up a sub-Fiber app for each request.
MiddlewareFromHTTP that transforms a standard Go HTTP middleware which takes and returns http.Handler, into a MiddlewareFunc suitable for use with our router.
NewBadRequestError for generic bad requests outside of validation context.
NewConflictError for requests that could not be completed due to a conflict.
No description provided by the author
TODO: We should make this asynchronous so that we can gather options in our app before we call fiber.New (since at that point it calls init and we are done).
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
NewMetadataAggregator creates a new aggregator.
NewMethodNotAllowedError for requests that use an unallowed HTTP method.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
NewTooManyRequestsError for rate-limiting scenarios.
No description provided by the author
NewValidationError.
No description provided by the author
SerializeAsContext will return any object as a PageContext instance.
No description provided by the author
No description provided by the author
ToMiddleware function to wrap handlers and run them as a middleware.
No description provided by the author
WithEnvironment sets the environment for error handling.
WithErrorHandlerMiddleware creates a middleware that handles errors for all routes in a group.
WithErrorMapper adds additional error mappers.
WithGetStackTrace adds additional error mappers.
WithLogger sets the logger for error handling.
No description provided by the author
WithStackTrace enables or disables stack traces.
No description provided by the author
WrapHandler function to wrap handlers that return error.

# Constants

not in RFC, just control "SameSite" attribute will not be set.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
POST
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Variables

No description provided by the author

# Structs

Common fields for both FiberRouter and HTTPRouter.
Cookie data for c.Cookie.
ErrorHandlerConfig allows customization of error handling behavior.
ErrorResponse represents the structure of error responses.
No description provided by the author
No description provided by the author
HTTPRouter implements Router for httprouter.
No description provided by the author
MetadataAggregator collects and merges metadata from multiple providers.
NamedHandler is a handler with a name for debugging/printing.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Parameter unifies the parameter definitions.
No description provided by the author
RequestBody unifies the request body definitions.
ResourceMetadata represents collected metadata about an API resource.
Response unifies the response definitions.
No description provided by the author
No description provided by the author
RouteDefinition represents all metadata about a route, combining both runtime routing information and metadata.
RouterError represents a custom error type for the router package.
No description provided by the author
Static configuration options.
ValidationError represents a validation error for a specific field.

# Interfaces

Context represents a generic HTTP context.
ContextStore is a request scoped, in-memoroy store to pass data between middleware/handlers in the same request in a fremework agnostic way.
No description provided by the author
MetadataProvider interface for components that can provide API metadata.
No description provided by the author
TODO: Maybe incorporate into Router[T].
No description provided by the author
No description provided by the author
No description provided by the author
Router represents a generic router interface.
No description provided by the author
Server represents a generic server interface.
No description provided by the author
No description provided by the author
Views is the interface that wraps the Render function.

# Type aliases

No description provided by the author
ErrorHandlerOption defines a function that can modify ErrorHandlerConfig.
ErrorMapper is a function that can map specific error types to RouterError.
Error Types.
No description provided by the author
HTTPMethod represents HTTP request methods.
No description provided by the author
No description provided by the author
No description provided by the author
ViewContext provide template values.
No description provided by the author