amaro

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2026 License: MIT Imports: 22 Imported by: 0

README ΒΆ

Amaro

πŸ”₯ The blazing fast, zero-dependency Go HTTP framework

Inspired by Hono.js, built for performance and simplicity.


Amaro is a lightweight, high-performance web framework for Go. It prioritizes zero allocations in the hot path, zero external dependencies, and a developer-friendly API that feels like modern JavaScript frameworks but with the power of Go.

πŸš€ Features

  • Zero Dependency: Runs on pure Go standard library.
  • Blazing Fast: Optimized Trie-based router with zero-allocation context pooling.
  • Decoupled Architecture: Router implementation is fully decoupled from the core framework.
  • Configurable Syntax: Support for customizable parameter delimiters (e.g. :id or {id}) via pluggable parsers.
  • Robust Static Serving: Built-in support for serving static files, SPAs, and directory browsing (configurable).
  • Production-Grade Middlewares: Includes Auth (Basic, Key, Session, RBAC), CORS, Cache, and more.
  • Group Routing: Organize routes with prefixes and shared middlewares.
  • Context Pooling: Reuses request contexts to minimize GC pressure.
  • Addon System: Extensible with powerful addons like OpenAPI generation and Streaming.

πŸ“¦ Installation

go get github.com/buildwithgo/amaro

⚑ Quick Start

package main

import (
    "net/http"
    "github.com/buildwithgo/amaro"
    "github.com/buildwithgo/amaro/routers"
)

func main() {
    // Initialize with the optimized TrieRouter
    app := amaro.New(amaro.WithRouter(routers.NewTrieRouter()))

    app.GET("/", func(c *amaro.Context) error {
        return c.String(http.StatusOK, "Hello, Amaro! πŸ”₯")
    })

    app.GET("/json", func(c *amaro.Context) error {
        return c.JSON(http.StatusOK, map[string]string{
            "message": "Blazing fast JSON",
        })
    })

    app.Run("8080")
}

πŸ› οΈ Advanced Configuration

Customizing Router Syntax

Amaro's TrieRouter is fully decoupled from the syntax it parses. You can define custom rules for identifying parameters using ParamParser functions.

// Custom parser for <id> syntax
customParser := func(segment string) (bool, string) {
    if len(segment) > 2 && segment[0] == '<' && segment[len(segment)-1] == '>' {
        return true, segment[1 : len(segment)-1]
    }
    return false, ""
}

config := routers.DefaultTrieRouterConfig()
config.ParamParser = customParser

r := routers.NewTrieRouter(routers.WithConfig(config))
app := amaro.New(amaro.WithRouter(r))

app.GET("/users/<id>", handler) // Matches /users/123
Static File Serving

Serve static files with robust support for SPAs (Single Page Applications).

app.StaticFS("/assets", os.DirFS("./public"))

// Or using the robust Static handler manually for more control
app.GET("/app/*filepath", amaro.StaticHandler(amaro.StaticConfig{
    Root: os.DirFS("./dist"),
    SPA:  true, // Serve index.html on 404
    Index: "index.html",
}))

πŸ›‘οΈ Middlewares

Amaro comes with a suite of production-grade middlewares.

Authentication & Authorization
import "github.com/buildwithgo/amaro/middlewares"

// Basic Auth
app.Use(middlewares.BasicAuth(func(user, pass string, c *amaro.Context) (bool, error) {
    return user == "admin" && pass == "secret", nil
}))

// API Key Auth
app.Use(middlewares.KeyAuth(func(key string, c *amaro.Context) (bool, error) {
    return key == "valid-api-key", nil
}))

// Session Auth (requires addons/sessions)
app.Use(middlewares.SessionAuth[User](validatorFunc))

// RBAC (Role-Based Access Control)
app.GET("/admin", middlewares.RBAC("admin", roleExtractor), adminHandler)
CORS & Caching
// CORS with options
app.Use(middlewares.CORS(middlewares.CORSConfig{
    AllowOrigins: []string{"https://example.com"},
    AllowCredentials: true,
}))

// Cache responses
store := cache.NewMemoryCache()
app.GET("/cached-data", middlewares.CachePage(store, 5*time.Minute), handler)

πŸ“– Cookbook

Accessing Path Parameters
app.GET("/user/:id", func(c *amaro.Context) error {
    id := c.PathParam("id") // Works with :id or {id} or configured syntax
    return c.String(200, "User ID: "+id)
})
Accessing Query Parameters
// GET /search?q=golang
app.GET("/search", func(c *amaro.Context) error {
    query := c.QueryParam("q")
    return c.String(200, "Searching for: "+query)
})

πŸ”Œ Addons

OpenAPI Generator

Amaro includes a built-in OpenAPI v3 generator to automatically document your API.

import "github.com/buildwithgo/amaro/addons/openapi"

// Create generator
gen := openapi.NewGenerator(openapi.Info{
    Title:   "My API",
    Version: "1.0.0",
})
// ... (see full docs for usage)

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

πŸ“„ License

This project is licensed under the MIT License - see the license file for details.

Documentation ΒΆ

Overview ΒΆ

Package amaro implements a blazing fast, zero-dependency, zero-allocation HTTP router and framework for Go.

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func DefaultParamParser ΒΆ added in v0.3.0

func DefaultParamParser(segment string) (bool, string)

DefaultParamParser implements the standard :param and {param} syntax.

func DefaultWildcardParser ΒΆ added in v0.3.0

func DefaultWildcardParser(segment string) (bool, string)

DefaultWildcardParser implements the standard *wildcard syntax.

Types ΒΆ

type App ΒΆ

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

App is the main entry point for the Amaro framework. It holds the router, global middlewares, and a context pool.

func New ΒΆ

func New(options ...AppOption) *App

New creates a new instance of the Amaro App with optional configuration.

func (*App) Add ΒΆ

func (a *App) Add(method, path string, handler Handler, middlewares ...Middleware) error

Add registers a new route with the specified method, path, handler, and middlewares.

func (*App) DELETE ΒΆ

func (a *App) DELETE(path string, handler Handler, middlewares ...Middleware) error

func (*App) Find ΒΆ

func (a *App) Find(method, path string) (*Route, error)

func (*App) GET ΒΆ

func (a *App) GET(path string, handler Handler, middlewares ...Middleware) error

GET registers a new GET route with a handler and optional route-specific middlewares.

func (*App) Group ΒΆ

func (a *App) Group(prefix string) *Group

func (*App) HEAD ΒΆ

func (a *App) HEAD(path string, handler Handler, middlewares ...Middleware) error

func (*App) OPTIONS ΒΆ

func (a *App) OPTIONS(path string, handler Handler, middlewares ...Middleware) error

func (*App) PATCH ΒΆ

func (a *App) PATCH(path string, handler Handler, middlewares ...Middleware) error

func (*App) POST ΒΆ

func (a *App) POST(path string, handler Handler, middlewares ...Middleware) error

func (*App) PUT ΒΆ

func (a *App) PUT(path string, handler Handler, middlewares ...Middleware) error

func (*App) Run ΒΆ

func (a *App) Run(address string) error

Run starts the HTTP server with graceful shutdown support.

func (*App) RunTLS ΒΆ added in v0.1.0

func (a *App) RunTLS(address, certFile, keyFile string) error

RunTLS starts the HTTPS server with graceful shutdown support.

func (*App) ServeHTTP ΒΆ

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

func (*App) Static ΒΆ added in v0.3.0

func (a *App) Static(pathPrefix, root string)

Static serves files from the local filesystem.

func (*App) StaticFS ΒΆ

func (a *App) StaticFS(pathPrefix string, fs fs.FS)

func (*App) Test ΒΆ added in v0.4.0

func (a *App) Test(req *http.Request) *httptest.ResponseRecorder

Test executes a request against the application and returns the response recorder. This is a helper for writing tests.

func (*App) Use ΒΆ

func (a *App) Use(middleware Middleware)

Use adds a global middleware to the application. Global middlewares are applied to all routes in the order they are added.

type AppOption ΒΆ

type AppOption func(*App)

AppOption defines a function to configure the App during initialization.

func WithErrorHandler ΒΆ added in v0.2.0

func WithErrorHandler(handler ErrorHandler) AppOption

WithErrorHandler returns an AppOption that configures the App to use the specified ErrorHandler.

func WithRouter ΒΆ

func WithRouter(router Router) AppOption

WithRouter returns an AppOption that configures the App to use the specified router.

type Context ΒΆ

type Context struct {
	Request *http.Request
	Writer  http.ResponseWriter
	Params  []Param // efficient slice instead of map
	Keys    map[string]interface{}
}

Context represents the context of the current HTTP request. It holds the request and response objects, URL parameters, and provides helper methods. It is designed to be reused via sync.Pool to minimize allocations.

func NewContext ΒΆ

func NewContext(w http.ResponseWriter, r *http.Request, options ...ContextOption) *Context

NewContext creates a new context for the request

func (*Context) AddParam ΒΆ

func (c *Context) AddParam(key, value string)

func (*Context) BindForm ΒΆ added in v0.4.0

func (c *Context) BindForm(v interface{}) error

BindForm binds the form parameters to the provided struct.

func (*Context) BindJSON ΒΆ added in v0.4.0

func (c *Context) BindJSON(v interface{}) error

BindJSON binds the request body to the provided struct.

func (*Context) BindQuery ΒΆ added in v0.4.0

func (c *Context) BindQuery(v interface{}) error

BindQuery binds the query parameters to the provided struct.

func (*Context) FormFile ΒΆ added in v0.1.0

func (c *Context) FormFile(name string) (*multipart.FileHeader, error)

FormFile returns the first file for the provided form key.

func (*Context) Get ΒΆ added in v0.1.0

func (c *Context) Get(key string) (value interface{}, exists bool)

Get retrieves a value from the context.

func (*Context) GetCookie ΒΆ

func (c *Context) GetCookie(name string) (*http.Cookie, error)

func (*Context) GetHeader ΒΆ

func (c *Context) GetHeader(key string) string

func (*Context) HTML ΒΆ

func (c *Context) HTML(statusCode int, html string) error

func (*Context) JSON ΒΆ

func (c *Context) JSON(statusCode int, v interface{}) error

func (*Context) PathParam ΒΆ

func (c *Context) PathParam(name string) string

func (*Context) QueryParam ΒΆ

func (c *Context) QueryParam(name string) string

func (*Context) Redirect ΒΆ

func (c *Context) Redirect(statusCode int, url string) error

func (*Context) Reset ΒΆ

func (c *Context) Reset(w http.ResponseWriter, r *http.Request)

Reset resets the context to be reused in sync.Pool

func (*Context) SaveFile ΒΆ added in v0.1.0

func (c *Context) SaveFile(file *multipart.FileHeader, dst string) error

SaveFile saves the uploaded file to the specified destination.

func (*Context) Set ΒΆ added in v0.1.0

func (c *Context) Set(key string, value interface{})

Set stores a new key-value pair in the context for this request.

func (*Context) SetCookie ΒΆ

func (c *Context) SetCookie(cookie *http.Cookie)

func (*Context) SetHeader ΒΆ

func (c *Context) SetHeader(key, value string)

func (*Context) Status ΒΆ

func (c *Context) Status(statusCode int)

func (*Context) String ΒΆ

func (c *Context) String(statusCode int, s string) error

type ContextOption ΒΆ

type ContextOption func(*Context)

type ErrorHandler ΒΆ added in v0.2.0

type ErrorHandler func(c *Context, err error, code int)

ErrorHandler is a function that handles errors occurred during request processing.

type Group ΒΆ

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

Group represents a route group with a common path prefix and shared middlewares.

func NewGroup ΒΆ

func NewGroup(prefix string, router Router) *Group

func (*Group) Add ΒΆ

func (g *Group) Add(method, path string, handler Handler, middlewares ...Middleware) error

func (*Group) DELETE ΒΆ

func (g *Group) DELETE(path string, handler Handler, middlewares ...Middleware) error

func (*Group) Find ΒΆ

func (g *Group) Find(method, path string) (*Route, error)

func (*Group) GET ΒΆ

func (g *Group) GET(path string, handler Handler, middlewares ...Middleware) error

func (*Group) Group ΒΆ

func (g *Group) Group(prefix string) *Group

func (*Group) HEAD ΒΆ

func (g *Group) HEAD(path string, handler Handler, middlewares ...Middleware) error

func (*Group) OPTIONS ΒΆ

func (g *Group) OPTIONS(path string, handler Handler, middlewares ...Middleware) error

func (*Group) PATCH ΒΆ

func (g *Group) PATCH(path string, handler Handler, middlewares ...Middleware) error

func (*Group) POST ΒΆ

func (g *Group) POST(path string, handler Handler, middlewares ...Middleware) error

func (*Group) PUT ΒΆ

func (g *Group) PUT(path string, handler Handler, middlewares ...Middleware) error

func (*Group) StaticFS ΒΆ

func (g *Group) StaticFS(pathPrefix string, fs fs.FS)

func (*Group) Use ΒΆ

func (g *Group) Use(middleware Middleware)

Use adds a middleware to the group. These middlewares are applied to all routes registered in this group.

type HTTPError ΒΆ added in v0.3.0

type HTTPError struct {
	Code     int
	Message  interface{}
	Internal error
}

HTTPError represents an error with an associated HTTP status code.

func NewHTTPError ΒΆ added in v0.3.0

func NewHTTPError(code int, message ...interface{}) *HTTPError

NewHTTPError creates a new HTTPError.

func (*HTTPError) Error ΒΆ added in v0.3.0

func (e *HTTPError) Error() string

func (*HTTPError) SetInternal ΒΆ added in v0.3.0

func (e *HTTPError) SetInternal(err error) *HTTPError

SetInternal sets the internal error.

func (*HTTPError) Unwrap ΒΆ added in v0.3.0

func (e *HTTPError) Unwrap() error

Unwrap returns the internal error.

type Handler ΒΆ

type Handler func(*Context) error

Handler is a function that handles an HTTP request. It returns an error which can be handled by middlewares or the framework.

func Compile ΒΆ

func Compile(handler Handler, middlewares ...Middleware) Handler

func StaticHandler ΒΆ added in v0.3.0

func StaticHandler(config StaticConfig) Handler

StaticHandler creates a handler that serves static files.

type Middleware ΒΆ

type Middleware func(next Handler) Handler

Middleware is a function that wraps a Handler to provide additional functionality.

func Chain ΒΆ

func Chain(middlewares ...Middleware) Middleware

func Recovery ΒΆ added in v0.3.0

func Recovery(opts ...RecoveryOption) Middleware

Recovery recovers from panics, logs the stack trace, and returns an Internal Server Error.

type Param ΒΆ

type Param struct {
	Key   string
	Value string
}

Param represents a single URL parameter, consisting of a key and a value.

type ParamParser ΒΆ added in v0.3.0

type ParamParser func(segment string) (bool, string)

ParamParser defines a function that checks if a path segment is a parameter. It returns true and the parameter name if it is, false otherwise.

type RecoveryOption ΒΆ added in v0.4.0

type RecoveryOption func(*recoveryConfig)

RecoveryOption configures the Recovery middleware.

func WithHTMLDebug ΒΆ added in v0.4.0

func WithHTMLDebug(enabled bool) RecoveryOption

WithHTMLDebug enables rendering a pretty HTML debug page for panics. WARNING: Do not use this in production as it exposes stack traces.

type Route ΒΆ

type Route struct {
	Method      string
	Path        string
	Handler     Handler
	Middlewares []Middleware
}

Route represents a registered route.

type Router ΒΆ

type Router interface {
	GET(path string, handler Handler, middlewares ...Middleware) error
	POST(path string, handler Handler, middlewares ...Middleware) error
	PUT(path string, handler Handler, middlewares ...Middleware) error
	DELETE(path string, handler Handler, middlewares ...Middleware) error
	PATCH(path string, handler Handler, middlewares ...Middleware) error
	OPTIONS(path string, handler Handler, middlewares ...Middleware) error
	HEAD(path string, handler Handler, middlewares ...Middleware) error
	Add(method, path string, handler Handler, middlewares ...Middleware) error
	Use(middleware Middleware)
	Group(prefix string) *Group
	Find(method, path string, ctx *Context) (*Route, error)
	StaticFS(pathPrefix string, fs fs.FS)
	Routes() []Route
}

Router is the interface that all router implementations must satisfy. It allows for swappable routing strategies.

type RouterConfig ΒΆ added in v0.3.0

type RouterConfig struct {
	ParamParser    ParamParser
	WildcardParser WildcardParser
}

RouterConfig defines configuration for Router.

func DefaultRouterConfig ΒΆ added in v0.3.0

func DefaultRouterConfig() RouterConfig

DefaultRouterConfig returns the default configuration.

type StaticConfig ΒΆ added in v0.3.0

type StaticConfig struct {
	// Root is the filesystem to serve from.
	Root fs.FS

	// Prefix is the URL path prefix.
	Prefix string

	// Index is the index file name (default: "index.html").
	Index string

	// Browse enables directory listing (default: false).
	Browse bool

	// SPA mode: if file not found, serve Index (default: false).
	SPA bool

	// ModifyResponse allows setting custom headers.
	ModifyResponse func(c *Context)
}

StaticConfig defines configuration for serving static files.

type WildcardParser ΒΆ added in v0.3.0

type WildcardParser func(segment string) (bool, string)

WildcardParser defines a function that checks if a path segment is a wildcard. It returns true and the wildcard name if it is, false otherwise.

Directories ΒΆ

Path Synopsis
addons
openapi
Package openapi provides a zero-dependency OpenAPI v3 specification generator for Amaro.
Package openapi provides a zero-dependency OpenAPI v3 specification generator for Amaro.

Jump to

Keyboard shortcuts

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