marten

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2026 License: MIT Imports: 16 Imported by: 0

README

Marten

A minimal, zero-dependency web framework for Go.

Go Reference Go Report Card CI License


Marten is a lightweight HTTP framework built entirely on Go's standard library. No external dependencies. No magic. Just clean, predictable code that gets out of your way.

Table of Contents

Installation

go get github.com/gomarten/marten

Quick Start

package main

import (
    "github.com/gomarten/marten"
    "github.com/gomarten/marten/middleware"
)

func main() {
    app := marten.New()
    
    app.Use(middleware.Logger)
    app.Use(middleware.Recover)

    app.GET("/", func(c *marten.Ctx) error {
        return c.OK(marten.M{"message": "Hello, World!"})
    })

    app.GET("/users/:id", func(c *marten.Ctx) error {
        id := c.ParamInt("id")
        return c.OK(marten.M{"id": id})
    })

    app.Run(":8080")
}

Features

Feature Description
Zero Dependencies Built entirely on Go's standard library
Fast Routing Radix tree router with path parameters and wildcards
Middleware Chainable middleware with 13 built-in options
Context Pooling Efficient memory reuse for high throughput
Response Helpers OK(), Created(), BadRequest(), NotFound(), and more
Typed Parameters ParamInt(), QueryInt(), QueryBool()
Graceful Shutdown Built-in support via RunGraceful()

Routing

// Path parameters
app.GET("/users/:id", handler)
app.GET("/files/*filepath", handler)

// Route groups
api := app.Group("/api/v1")
api.GET("/users", listUsers)
api.POST("/users", createUser)

// All HTTP methods
app.GET("/resource", handler)
app.POST("/resource", handler)
app.PUT("/resource", handler)
app.DELETE("/resource", handler)
app.PATCH("/resource", handler)
app.HEAD("/resource", handler)
app.OPTIONS("/resource", handler)

Middleware

Built-in middleware:

import "github.com/gomarten/marten/middleware"

app.Use(middleware.Logger)           // Request logging
app.Use(middleware.Recover)          // Panic recovery
app.Use(middleware.CORS(config))     // Cross-origin requests
app.Use(middleware.RateLimit(cfg))   // Rate limiting
app.Use(middleware.BasicAuth(cfg))   // Basic authentication
app.Use(middleware.Timeout(5*time.Second))
app.Use(middleware.Compress(cfg))    // Gzip compression
app.Use(middleware.Secure(cfg))      // Security headers
app.Use(middleware.RequestID)        // Request ID injection
app.Use(middleware.BodyLimit(1*middleware.MB))
app.Use(middleware.ETag)             // ETag caching
app.Use(middleware.NoCache)          // Cache prevention

Route-specific middleware:

app.GET("/admin", adminHandler, authMiddleware, logMiddleware)

Context API

func handler(c *marten.Ctx) error {
    // Path and query parameters
    id := c.Param("id")
    page := c.QueryInt("page")
    
    // Request data
    ip := c.ClientIP()
    token := c.Bearer()
    
    // JSON binding
    var user User
    if err := c.Bind(&user); err != nil {
        return c.BadRequest("invalid JSON")
    }
    
    // Responses
    return c.OK(data)              // 200
    return c.Created(data)         // 201
    return c.NoContent()           // 204
    return c.BadRequest("error")   // 400
    return c.NotFound("not found") // 404
}

Configuration

// Trailing slash handling
app.SetTrailingSlash(marten.TrailingSlashRedirect)

// Custom 404 handler
app.NotFound(func(c *marten.Ctx) error {
    return c.JSON(404, marten.E("page not found"))
})

// Custom error handler
app.OnError(func(c *marten.Ctx, err error) {
    c.JSON(500, marten.E(err.Error()))
})

// Graceful shutdown
app.RunGraceful(":8080", 10*time.Second)

Benchmarks

Marten performs on par with Gin and Echo while maintaining zero dependencies.

Benchmark Marten Gin Echo Chi
Static Route 1464 ns/op 1336 ns/op 1436 ns/op 2202 ns/op
Param Route 1564 ns/op 1418 ns/op 1472 ns/op 2559 ns/op
JSON Response 1755 ns/op 2050 ns/op 1835 ns/op 1868 ns/op

See benchmarks/ for full comparison with Gin, Echo, Chi and Fiber.

Examples

Example Description
basic Hello World, JSON, path and query params
crud-api RESTful API with validation
auth-jwt JWT authentication
middleware Built-in and custom middleware
groups Route groups and versioning
error-handling Custom error types and handlers
file-server Static files and SPA fallback
marten-demo Full web app with auth and templates

Documentation

Full documentation available at gomarten.github.io/docs

Contributing

See CONTRIBUTING.md for guidelines.

Community & Discussions

Questions or ideas?
Join the discussion: https://github.com/gomarten/marten/discussions

License

MIT License. See LICENSE for details.

Documentation

Overview

Package marten is a minimal, elegant web framework for Go. Philosophy: The framework you reach for when you want nothing in the way.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func E

func E(message string) map[string]string

E creates a simple error response map.

Types

type App

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

App is the core of Marten.

func New

func New() *App

New creates a new Marten application.

func (*App) OnError

func (a *App) OnError(fn func(*Ctx, error))

OnError sets a custom error handler.

func (*App) OnShutdown added in v0.1.2

func (a *App) OnShutdown(fn func())

OnShutdown registers a callback to run when the server shuts down.

func (*App) OnStart added in v0.1.2

func (a *App) OnStart(fn func())

OnStart registers a callback to run when the server starts.

func (*App) Run

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

Run starts the server on the given address.

func (*App) RunGraceful

func (a *App) RunGraceful(addr string, timeout time.Duration) error

RunGraceful starts the server with graceful shutdown support.

func (*App) ServeHTTP

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

ServeHTTP implements http.Handler.

func (*App) SetTrailingSlash

func (a *App) SetTrailingSlash(mode TrailingSlashMode)

SetTrailingSlash configures trailing slash handling.

type BindError

type BindError struct {
	Message string
}

BindError represents a binding error.

func (*BindError) Error

func (e *BindError) Error() string

type Ctx

type Ctx struct {
	Request *http.Request
	Writer  http.ResponseWriter
	// contains filtered or unexported fields
}

Ctx wraps a request with helpers for clean handler code.

func (*Ctx) BadRequest

func (c *Ctx) BadRequest(message string) error

BadRequest sends a 400 JSON error response.

func (*Ctx) Bearer

func (c *Ctx) Bearer() string

Bearer extracts the Bearer token from Authorization header.

func (*Ctx) Bind

func (c *Ctx) Bind(v any) error

Bind decodes request body into v based on Content-Type. Supports application/json, application/x-www-form-urlencoded, and multipart/form-data.

func (*Ctx) BindValid

func (c *Ctx) BindValid(v any, validate func() error) error

BindValid decodes JSON and validates using the provided function.

func (*Ctx) Blob

func (c *Ctx) Blob(code int, contentType string, data []byte) error

Blob writes a binary response with the given content type.

func (*Ctx) ClientIP

func (c *Ctx) ClientIP() string

ClientIP extracts the client IP intelligently.

func (*Ctx) Context

func (c *Ctx) Context() context.Context

Context returns the request's context.

func (*Ctx) Cookie

func (c *Ctx) Cookie(name string) string

Cookie returns a cookie value by name.

func (*Ctx) Created

func (c *Ctx) Created(v any) error

Created sends a 201 JSON response.

func (*Ctx) File

func (c *Ctx) File(name string) (*multipart.FileHeader, error)

File returns a file from multipart form.

func (*Ctx) Forbidden

func (c *Ctx) Forbidden(message string) error

Forbidden sends a 403 JSON error response.

func (*Ctx) FormValue

func (c *Ctx) FormValue(name string) string

FormValue returns a form value by name.

func (*Ctx) Get

func (c *Ctx) Get(key string) any

Get retrieves a value from the request context.

func (*Ctx) GetBool

func (c *Ctx) GetBool(key string) bool

GetBool retrieves a bool value from the request context.

func (*Ctx) GetHeader

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

GetHeader returns a request header value.

func (*Ctx) GetInt

func (c *Ctx) GetInt(key string) int

GetInt retrieves an int value from the request context.

func (*Ctx) GetString

func (c *Ctx) GetString(key string) string

GetString retrieves a string value from the request context.

func (*Ctx) HTML

func (c *Ctx) HTML(code int, html string) error

HTML writes an HTML response.

func (*Ctx) Header

func (c *Ctx) Header(key, value string) *Ctx

Header sets a response header.

func (*Ctx) IsAJAX

func (c *Ctx) IsAJAX() bool

IsAJAX returns true if X-Requested-With is XMLHttpRequest.

func (*Ctx) IsJSON

func (c *Ctx) IsJSON() bool

IsJSON returns true if Content-Type is application/json.

func (*Ctx) JSON

func (c *Ctx) JSON(code int, v any) error

JSON writes a JSON response.

func (*Ctx) Method

func (c *Ctx) Method() string

Method returns the request method.

func (*Ctx) NoContent

func (c *Ctx) NoContent() error

NoContent sends a 204 response.

func (*Ctx) NotFound

func (c *Ctx) NotFound(message string) error

NotFound sends a 404 JSON error response.

func (*Ctx) OK

func (c *Ctx) OK(v any) error

OK sends a 200 JSON response.

func (*Ctx) Param

func (c *Ctx) Param(name string) string

Param returns a path parameter by name.

func (*Ctx) ParamInt

func (c *Ctx) ParamInt(name string) int

ParamInt returns a path parameter as int (0 if invalid).

func (*Ctx) ParamInt64

func (c *Ctx) ParamInt64(name string) int64

ParamInt64 returns a path parameter as int64 (0 if invalid).

func (*Ctx) Path

func (c *Ctx) Path() string

Path returns the request path.

func (*Ctx) Query

func (c *Ctx) Query(name string) string

Query returns a query parameter by name.

func (*Ctx) QueryBool

func (c *Ctx) QueryBool(name string) bool

QueryBool returns a query parameter as bool (false if invalid).

func (*Ctx) QueryDefault

func (c *Ctx) QueryDefault(name, def string) string

QueryDefault returns a query parameter or default if empty.

func (*Ctx) QueryInt

func (c *Ctx) QueryInt(name string) int

QueryInt returns a query parameter as int (0 if invalid).

func (*Ctx) QueryInt64

func (c *Ctx) QueryInt64(name string) int64

QueryInt64 returns a query parameter as int64 (0 if invalid).

func (*Ctx) QueryParams

func (c *Ctx) QueryParams() url.Values

QueryParams returns all query parameters.

func (*Ctx) QueryValues

func (c *Ctx) QueryValues(name string) []string

QueryValues returns all values for a query parameter.

func (*Ctx) Redirect

func (c *Ctx) Redirect(code int, url string) error

Redirect sends a redirect response.

func (*Ctx) RequestID

func (c *Ctx) RequestID() string

RequestID returns a unique request identifier.

func (*Ctx) Reset

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

Reset clears the context for reuse.

func (*Ctx) ServerError

func (c *Ctx) ServerError(message string) error

ServerError sends a 500 JSON error response.

func (*Ctx) Set

func (c *Ctx) Set(key string, value any)

Set stores a value in the request context.

func (*Ctx) SetCookie

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

SetCookie sets a response cookie.

func (*Ctx) SetParam

func (c *Ctx) SetParam(key, value string)

SetParam sets a path parameter (used internally by router).

func (*Ctx) Status

func (c *Ctx) Status(code int) *Ctx

Status sets the response status code.

func (*Ctx) StatusCode

func (c *Ctx) StatusCode() int

StatusCode returns the response status code (0 if not yet written).

func (*Ctx) Stream

func (c *Ctx) Stream(code int, contentType string, r io.Reader) error

Stream writes data from a reader to the response.

func (*Ctx) Text

func (c *Ctx) Text(code int, text string) error

Text writes a plain text response.

func (*Ctx) Unauthorized

func (c *Ctx) Unauthorized(message string) error

Unauthorized sends a 401 JSON error response.

func (*Ctx) Written

func (c *Ctx) Written() bool

Written returns true if the response has been written.

type Group

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

Group represents a route group with shared prefix and middleware.

func (*Group) DELETE

func (g *Group) DELETE(path string, h Handler, mw ...Middleware)

DELETE registers a DELETE route within the group.

func (*Group) GET

func (g *Group) GET(path string, h Handler, mw ...Middleware)

GET registers a GET route within the group.

func (*Group) Group

func (g *Group) Group(prefix string, mw ...Middleware) *Group

Group creates a nested group.

func (*Group) HEAD

func (g *Group) HEAD(path string, h Handler, mw ...Middleware)

HEAD registers a HEAD route within the group.

func (*Group) Handle

func (g *Group) Handle(method, path string, h Handler, mw ...Middleware)

Handle registers a route within the group.

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, h Handler, mw ...Middleware)

OPTIONS registers an OPTIONS route within the group.

func (*Group) PATCH

func (g *Group) PATCH(path string, h Handler, mw ...Middleware)

PATCH registers a PATCH route within the group.

func (*Group) POST

func (g *Group) POST(path string, h Handler, mw ...Middleware)

POST registers a POST route within the group.

func (*Group) PUT

func (g *Group) PUT(path string, h Handler, mw ...Middleware)

PUT registers a PUT route within the group.

func (*Group) Use

func (g *Group) Use(mw ...Middleware)

Use adds middleware to the group.

type Handler

type Handler func(*Ctx) error

Handler is a function that handles an HTTP request.

type M

type M map[string]any

M is a shorthand for map[string]any.

type Middleware

type Middleware func(Handler) Handler

Middleware wraps a handler with additional behavior.

func Chain

func Chain(mw ...Middleware) Middleware

Chain composes multiple middleware into a single middleware.

type Route

type Route struct {
	Method string
	Path   string
}

Route represents a registered route.

type Router

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

Router handles HTTP routing with a radix tree.

func NewRouter

func NewRouter() *Router

NewRouter creates a new router.

func (*Router) DELETE

func (r *Router) DELETE(path string, h Handler, mw ...Middleware)

DELETE registers a DELETE route.

func (*Router) GET

func (r *Router) GET(path string, h Handler, mw ...Middleware)

GET registers a GET route.

func (*Router) Group

func (r *Router) Group(prefix string, mw ...Middleware) *Group

Group creates a new route group with the given prefix.

func (*Router) HEAD

func (r *Router) HEAD(path string, h Handler, mw ...Middleware)

HEAD registers a HEAD route.

func (*Router) Handle

func (r *Router) Handle(method, path string, h Handler, mw ...Middleware)

Handle registers a route with optional route-specific middleware. Panics if a conflicting param route is detected (e.g., :id vs :name at same position).

func (*Router) NotFound

func (r *Router) NotFound(h Handler)

NotFound sets a custom 404 handler.

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, h Handler, mw ...Middleware)

OPTIONS registers an OPTIONS route.

func (*Router) PATCH

func (r *Router) PATCH(path string, h Handler, mw ...Middleware)

PATCH registers a PATCH route.

func (*Router) POST

func (r *Router) POST(path string, h Handler, mw ...Middleware)

POST registers a POST route.

func (*Router) PUT

func (r *Router) PUT(path string, h Handler, mw ...Middleware)

PUT registers a PUT route.

func (*Router) Routes

func (r *Router) Routes() []Route

Routes returns all registered routes for debugging.

func (*Router) SetTrailingSlash

func (r *Router) SetTrailingSlash(mode TrailingSlashMode)

SetTrailingSlash configures trailing slash handling.

func (*Router) Use

func (r *Router) Use(mw ...Middleware)

Use adds global middleware.

type TrailingSlashMode

type TrailingSlashMode int

TrailingSlashMode defines how trailing slashes are handled.

const (
	// TrailingSlashIgnore treats /users and /users/ as the same (default)
	TrailingSlashIgnore TrailingSlashMode = iota
	// TrailingSlashRedirect redirects to the canonical path (301)
	TrailingSlashRedirect
	// TrailingSlashStrict treats /users and /users/ as different routes
	TrailingSlashStrict
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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