chain

package module
v1.0.12 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: MIT Imports: 32 Imported by: 0

README


A high-performance, production-ready HTTP router for Go with built-in crypto, pub/sub, and real-time socket support.

Go Version GoDoc


Chain is a lightweight, high-performance HTTP router and distributed systems toolkit for Go. It provides an optimized routing engine with middleware support, cryptographic utilities, a cluster-aware pub/sub system, and real-time WebSocket-like channels over SSE.

Features

  • Optimized HTTP Router — Segment-based routing with static route caching, wildcard support, and priority-based matching
  • Middleware System — Flexible middleware chain with route-specific and global scoping
  • Data Binding — Automatic binding for JSON, XML, Form, Query, Path, and Header parameters with validation
  • Cryptographic Utilities — AES-GCM encryption, PBKDF2 key derivation, HMAC message signing, and key rotation via Keyring
  • Pub/Sub System — Cluster-aware publish/subscribe with optional encryption and compression
  • Socket & Channels — Real-time multiplexed communication over Server-Sent Events (SSE)
  • Session Management — Cookie-based sessions with optional encryption and signing
  • Request Timeouts — Per-route and global timeout enforcement with 503 response on deadline exceeded
  • Graceful Shutdown — Production-ready server lifecycle with SIGINT/SIGTERM handling, in-flight request draining, and lifecycle hooks

Installation

go get github.com/nidorx/chain

Requirements: Go 1.25 or later.

Quick Start

Minimal Server

package main

import (
	"log"
	"net/http"

	"github.com/nidorx/chain"
)

func main() {
	r := chain.New()

	r.GET("/", func(ctx *chain.Context) error {
		ctx.Json(map[string]string{"message": "Hello, Chain!"})
		return nil
	})

	log.Println("Server starting on :8080")
	log.Fatal(http.ListenAndServe(":8080", r))
}

With Middleware and Route Groups

package main

import (
	"log"
	"net/http"
	"time"

	"github.com/nidorx/chain"
)

func main() {
	r := chain.New()

	// Global logging middleware
	r.Use(func(ctx *chain.Context, next func() error) error {
		start := time.Now()
		err := next()
		log.Printf("[%d] %s %s — %v", ctx.GetStatus(), ctx.Method(), ctx.URL().Path, time.Since(start))
		return err
	})

	// API v1 group with auth middleware
	api := r.Group("/api")
	api.Use(func(ctx *chain.Context, next func() error) error {
		if ctx.GetHeader("Authorization") == "" {
			ctx.Unauthorized(map[string]string{"error": "missing authorization"})
			return nil
		}
		return next()
	})

	v1 := api.Group("/v1")
	v1.GET("/users", listUsers)
	v1.POST("/users", createUser)
	v1.GET("/users/:id", getUser)

	log.Fatal(http.ListenAndServe(":8080", r))
}

func listUsers(ctx *chain.Context) error   { ctx.Json(map[string]string{"action": "list"}); return nil }
func createUser(ctx *chain.Context) error  { ctx.Json(map[string]string{"action": "create"}); return nil }
func getUser(ctx *chain.Context) error     { ctx.Json(map[string]string{"id": ctx.GetParam("id")}); return nil }

With Data Binding and Validation

package main

import (
	"log"
	"net/http"

	"github.com/nidorx/chain"
)

type CreateUser struct {
	Name  string `json:"name"  binding:"required,min=3"`
	Email string `json:"email" binding:"required,email"`
}

func main() {
	r := chain.New()

	r.POST("/users", func(ctx *chain.Context) error {
		var u CreateUser
		if err := ctx.BindJSON(&u); err != nil {
			return err // automatically returns 400 with validation details
		}
		ctx.Created(u)
		return nil
	})

	log.Fatal(http.ListenAndServe(":8080", r))
}

Router

router.png

chain has a lightweight high performance HTTP request router (also called multiplexer or just mux for short) for Go. In contrast to the default mux of Go's net/http package, this router supports variables in the routing pattern and matches against the request method. It also scales better.

  • Optimized HTTP router which smartly prioritize routes
  • Build robust and scalable RESTful APIs
  • Extensible Middleware framework
  • Handy functions to send variety of HTTP responses
  • Centralized HTTP error handling
package main

import (
	"github.com/nidorx/chain"
	"log"
	"net/http"
)

func main() {
	router := chain.New()

	// Middleware
	router.Use(func(ctx *chain.Context, next func() error) error {
		println("first middleware")
		return next()
	})

	router.Use("GET", "/*", func(ctx *chain.Context) {
		println("second middleware")
	})

	// Handler
	router.GET("/", func(ctx *chain.Context) {
		ctx.Write([]byte("Hello World!"))
	})

	// Grouping
	v1 := router.Group("/v1")
	{
		v1.GET("/users", func(ctx *chain.Context) {
			ctx.Write([]byte("[001]"))
		})
	}

	v2 := router.Group("/v2")
	{
		v2.GET("/users", func(ctx *chain.Context) {
			ctx.Write([]byte("[002]"))
		})
	}

	if err := http.ListenAndServe("localhost:8080", router); err != nil {
		log.Fatalf("ListenAndServe: %v", err)
	}
}

More about Router

PubSub

pubsub.png

Realtime Publisher/Subscriber service.

You can use the functions in this module to subscribe and broadcast messages:

package main

import (
	"fmt"
	"github.com/nidorx/chain"
	"github.com/nidorx/chain/pubsub"
	"time"
)

type MyDispatcher struct {
}

func (d *MyDispatcher) Dispatch(topic string, message any, from string) {
	println(fmt.Sprintf("New Message. Topic: %s, Content: %s", topic, message))
}

func main() {

	dispatcher := &MyDispatcher{}
	serializer := &chain.JsonSerializer{}

	pubsub.Subscribe("user:123", dispatcher)

	bytes, _ := serializer.Encode(map[string]any{
		"Event": "user_update",
		"Payload": map[string]any{
			"Id":   6,
			"Name": "Gabriel",
		},
	})
	pubsub.Broadcast("user:123", bytes)
	pubsub.Broadcast("user:123", []byte("Message 2"))

	// await
	<-time.After(time.Millisecond * 10)

	pubsub.Unsubscribe("user:123", dispatcher)

	pubsub.Broadcast("user:123", []byte("Message Ignored"))

	// await
	<-time.After(time.Millisecond * 10)
}

More about PubSub

Socket & Channels

socket.png

A socket implementation that multiplexes messages over channels.

Once connected to a socket, incoming and outgoing events are routed to channels. The incoming client data is routed to channels via transports. It is the responsibility of the socket to tie transports and channels together.

Chain ships with a JavaScript implementation that interacts with backend and can be used as reference for those interested in implementing custom clients.

Server

package main

import (
	"github.com/nidorx/chain"
	"github.com/nidorx/chain/socket"
	"log"
	"net/http"
)

func main() {
	router := chain.New()

	router.Configure("/socket", AppSocket)

	if err := http.ListenAndServe(":8080", router); err != nil {
		log.Fatalf("ListenAndServe: %v", err)
	}
}

var AppSocket = &socket.Handler{
	Channels: []*socket.Channel{
		socket.NewChannel("chat:*", chatChannel),
	},
}

func chatChannel(channel *socket.Channel) {

	channel.Join("chat:lobby", func(params any, socket *socket.Socket) (reply any, err error) {
		return
	})

	channel.HandleIn("my_event", func(event string, payload any, socket *socket.Socket) (reply any, err error) {
		reply = "Ok"

		socket.Push("other_event", map[string]any{"value": 1})
		return
	})
}

Client (javascript)

const socket = chain.Socket('/socket')
socket.connect()

const channel = socket.channel("chat:lobby", {param1: 'foo'})
channel.join()

channel.push('my_event', {name: $inputName.value})
    .on('ok', (reply) => chain.log('MyEvent', reply))


channel.on('other_event', (message) => chain.log('OtherEvent', message))

More about Socket & Channels

Crypto

Simplify and standardize the use and maintenance of symmetric cryptographic keys.

Features:

  • SecretKeyBase Solution that allows your application to have a single security key and from that it is possible to generate an infinite number of derived keys used in the most diverse features of your project.
  • Keyring Allows you to enable key rotation, allowing encryption processes to be performed with a new key and data encrypted with old keys can still be decrypted.
  • KeyGenerator: It can be used to derive a number of keys for various purposes from a given secret. This lets applications have a single secure secret, but avoid reusing that key in multiple incompatible contexts.
  • MessageVerifier: makes it easy to generate and verify messages which are signed to prevent tampering.
  • MessageEncryptor is a simple way to encrypt values which get stored somewhere you don't trust.

More about Crypto

Routing Patterns

Chain supports flexible routing with static, parameterized, and wildcard segments.

// Static route
r.GET("/health", healthHandler)

// Parameterized routes
r.GET("/users/:id", getUser)
r.GET("/users/:user_id/posts/:post_id", getPost)

// Wildcard routes (matches rest of path)
r.GET("/assets/*filepath", serveAsset)

// Mixed patterns
r.GET("/api/:version/users/:id/*path", mixedHandler)

Route Groups

Organize routes under common prefixes with shared middleware.

api := r.Group("/api")
api.Use(authMiddleware)

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

Middleware

Middleware functions run before and after request handlers. Register globally, per-route, or on groups.

// Global middleware
r.Use(loggingMiddleware)

// Route-specific middleware
r.Use("/admin/*", adminAuthMiddleware)
r.Use("POST", "/api/*", csrfMiddleware)

// Middleware signature
func middleware(ctx *chain.Context, next func() error) error {
    // before handler
    err := next()
    // after handler
    return err
}

Chain provides built-in helper middlewares:

chain.MaxBytesMiddleware(10 << 20)      // Limit request body to 10MB
chain.ContentTypeMiddleware("application/json") // Restrict content types

Context

The *chain.Context encapsulates the request and response, providing convenient methods for data access and response writing.

Request Access

ctx.GetParam("id")          // Path parameter
ctx.QueryParam("page", "1") // Query param with default
ctx.GetHeader("Accept")     // Request header
ctx.GetCookie("session")    // Cookie
ctx.BodyBytes()             // Request body
ctx.Method()                // HTTP method
ctx.URL()                   // Request URL
ctx.Ip()                    // Client IP
ctx.UserAgent()             // User-Agent

Response Writing

ctx.Json(data)              // JSON response
ctx.Write([]byte("raw"))    // Raw bytes
ctx.Status(201)             // Set status code
ctx.Status(201, "created")  // Status code with text content
ctx.Status(201, []byte{})   // Status code with binary content
ctx.Status(201, data)       // Status code with JSON content

// Convenience methods (all accept optional content)
ctx.OK()                    // 200 OK
ctx.OK("success")           // 200 OK with text
ctx.OK(data)                // 200 OK with JSON
ctx.Created()               // 201 Created
ctx.Created(data)           // 201 Created with JSON
ctx.NoContent()             // 204 No Content
ctx.BadRequest()            // 400 Bad Request
ctx.BadRequest("error")     // 400 with custom message
ctx.BadRequest(data)        // 400 with JSON error
ctx.NotFound()              // 404 Not Found
ctx.NotFound("missing")     // 404 with custom message
ctx.Redirect("/new", 301)   // Redirect
ctx.SetCookie(cookie)       // Set cookie
ctx.ServeContent(data, name, modTime) // Serve with Range support

Response Hooks

ctx.BeforeSend(func() { /* modify headers before send */ })
ctx.AfterSend(func() { /* cleanup, metrics */ })

Request Timeouts

Chain provides request timeout enforcement with proper context cancellation via the middlewares/timeout package:

import "github.com/nidorx/chain/middlewares/timeout"

// Global timeout (all routes)
r.Use(timeout.New(timeout.Config{
    Timeout: 30 * time.Second,
}))

// Path-scoped timeout
r.Use("/api/*", timeout.New(timeout.Config{
    Timeout: 15 * time.Second,
}))

When a timeout occurs:

  1. The request context is cancelled
  2. All context-aware operations stops (database queries, HTTP clients, etc.)
  3. A 503 Service Unavailable is returned (if response not yet written)

Handlers should respect context cancellation for proper timeout enforcement:

r.GET("/db", func(ctx *chain.Context) error {
    // Database driver will respect context cancellation
    rows, err := db.QueryContext(ctx.Request.Context(), "SELECT ...")
    if err != nil {
        return err // context.Canceled on timeout
    }
    return nil
})

See Timeout Middleware Documentation for details.

Graceful Shutdown

Chain provides production-ready graceful shutdown:

server := chain.NewServer(r, ":8080")

// Optional: lifecycle hooks
server.OnShutdown(func() { log.Println("Shutting down...") })
server.OnStop(func() { log.Println("All requests completed") })

if err := server.ListenAndServe(); err != nil {
    log.Fatal(err)
}

Handles SIGINT/SIGTERM, stops accepting connections, waits for in-flight requests (default 30s).

Data Binding

Chain automatically binds request data to Go structs.

type User struct {
    ID    string `json:"id"    path:"id"`
    Name  string `json:"name"  query:"name" binding:"required"`
    Email string `json:"email" binding:"required,email"`
    Role  string `header:"X-Role"`
}

// Auto-detect binding (JSON, XML, Form, Query)
var u User
if err := ctx.Bind(&u); err != nil { /* 400 returned automatically */ }

// Explicit binding (returns error without setting status)
if err := ctx.ShouldBindJSON(&u); err != nil { /* handle error */ }

// Path, Query, Header binding
ctx.BindPath(&u)
ctx.BindQuery(&u)
ctx.BindHeader(&u)

Validation

Chain integrates go-playground/validator for struct validation.

type CreateUser struct {
    Name     string `json:"name"     binding:"required,min=3,max=100"`
    Email    string `json:"email"    binding:"required,email"`
    Password string `json:"password" binding:"required,min=8"`
    Age      int    `json:"age"      binding:"min=0,max=150"`
}

Cryptography

Chain provides comprehensive cryptographic utilities built on Go's standard library.

// Set secret key at startup
chain.SetSecretKeyBase(os.Getenv("SECRET_KEY_BASE"))

// AES-GCM encryption
encrypted, err := chain.Crypto().Encrypt(key, data, aad)
decrypted, err := chain.Crypto().Decrypt(key, encrypted, aad)

// Message signing (HMAC)
signature := chain.Crypto().MessageSign(key, message, "sha256")
decoded, err := chain.Crypto().MessageVerify(key, signature)

// Key derivation (PBKDF2)
derivedKey := chain.Crypto().KeyGenerate(secret, salt, 216000, 32, "sha256")

// Keyring for key rotation
keyring := chain.NewKeyring("salt", 216000, 32, "sha256")
encrypted, _ := keyring.Encrypt(data, aad)
decrypted, _ := keyring.Decrypt(encrypted, aad)

Examples

Runnable examples are available in the examples/ directory:

Example Description
basic-server Minimal HTTP server
route-groups Organized route grouping
middleware Custom middleware chain
data-binding JSON/Form binding
validation Request validation
crypto-basics Encryption/decryption
message-signing Signed messages
file-upload Multipart form handling
error-handling Global error handling
router Full router demo
pubsub Pub/sub demo
crypto Crypto examples
socket-chat Real-time chat with SSE
socket-cluster Clustered sockets with pub/sub

Documentation

Document Description
API Reference Complete API with examples
Architecture Guide System design and request lifecycle
Security Guidelines Security best practices
Evolution Roadmap Project roadmap
Comprehensive Analysis Code review and assessment

Benchmarks

Chain's segment-based routing algorithm with static route caching delivers competitive performance:

BenchmarkStaticRoute       2153128    548.4 ns/op    288 B/op    4 allocs/op
BenchmarkParamRoute         913468   1279 ns/op      720 B/op   11 allocs/op
BenchmarkMiddlewareChain   7230347    166.7 ns/op      0 B/op    0 allocs/op

See benchmark_test.go for the full benchmark suite.

Contributing

Contributions are welcome! Please follow these guidelines:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/my-feature)
  3. Commit your changes (git commit -am 'Add my feature')
  4. Push to the branch (git push origin feature/my-feature)
  5. Open a Pull Request

Development

# Run tests
go test ./...

# Run benchmarks
go test -bench=. -benchmem ./...

# Check for race conditions
go test -race ./...

License

Chain is released under the MIT License.

Documentation

Overview

Copyright 2014 Manu Martinez-Almeida. All rights reserved. see: https://github.com/gin-gonic/gin/blob/master/binding/binding.go

Copyright 2014 Manu Martinez-Almeida. All rights reserved. see: https://github.com/gin-gonic/gin/blob/master/binding/form.go

Copyright 2014 Manu Martinez-Almeida. All rights reserved. see: https://github.com/gin-gonic/gin/blob/master/binding/form_mapping.go

Copyright 2019 Gin Core Team. All rights reserved. see: https://github.com/gin-gonic/gin/blob/master/binding/multipart_form_mapping.go

Copyright 2022 Gin Core Team. All rights reserved. see: https://github.com/gin-gonic/gin/blob/master/binding/header.go

Copyright 2014 Manu Martinez-Almeida. All rights reserved. see: https://github.com/gin-gonic/gin/blob/master/binding/json.go

Copyright 2018 Gin Core Team. All rights reserved. see: https://github.com/gin-gonic/gin/blob/master/binding/uri.go

Copyright 2017 Manu Martinez-Almeida. All rights reserved. see: https://github.com/gin-gonic/gin/blob/master/binding/query.go

Copyright 2017 Manu Martinez-Almeida. All rights reserved. see: https://github.com/gin-gonic/gin/blob/master/binding/default_validator.go

Copyright 2014 Manu Martinez-Almeida. All rights reserved. see: https://github.com/gin-gonic/gin/blob/master/binding/xml.go

Index

Constants

View Source
const DefaultMaxHeaderLength = 4096

DefaultMaxHeaderLength is the default maximum length for header values

View Source
const DefaultMaxQueryParameterLength = 1024

DefaultMaxQueryParameterLength is the default maximum length for query parameters

View Source
const DefaultMaxRequestBodySize = 10 << 20

DefaultMaxRequestBodySize is the default maximum request body size (10MB)

View Source
const DefaultShutdownTimeout = 30 * time.Second

DefaultShutdownTimeout is the default timeout for graceful shutdown.

Variables

View Source
var (

	// ErrConvertMapStringSlice can not convert to map[string][]string
	ErrConvertMapStringSlice = errors.New("can not convert to map slices of strings")

	// ErrConvertToMapString can not convert to map[string]string
	ErrConvertToMapString = errors.New("can not convert to map of strings")
)
View Source
var (
	// ErrMultiFileHeader multipart.FileHeader invalid
	ErrMultiFileHeader = errors.New("unsupported field type for multipart.FileHeader")

	// ErrMultiFileHeaderLenInvalid array for []*multipart.FileHeader len invalid
	ErrMultiFileHeaderLenInvalid = errors.New("unsupported len of array for []*multipart.FileHeader")
)
View Source
var (
	// ErrInvalidRoutePath is returned when a route path doesn't start with '/'
	ErrInvalidRoutePath = errors.New("route path must begin with '/'")

	// ErrEmptyRoutePath is returned when a route path is empty
	ErrEmptyRoutePath = errors.New("route path cannot be empty")

	// ErrInvalidRouteMethod is returned when a route method is empty or invalid
	ErrInvalidRouteMethod = errors.New("route method must not be empty")

	// ErrInvalidRouteHandler is returned when a route handler is nil or invalid
	ErrInvalidRouteHandler = errors.New("invalid route handler")

	// ErrRequestBodyTooLarge is returned when the request body exceeds the maximum allowed size
	ErrRequestBodyTooLarge = errors.New("request body too large")

	// ErrInvalidContentType is returned when the Content-Type header is invalid or unsupported
	ErrInvalidContentType = errors.New("invalid or unsupported Content-Type")

	// ErrInvalidHeader is returned when a header value is malformed
	ErrInvalidHeader = errors.New("invalid header format")

	// ErrMissingParameter is returned when a required route parameter is missing
	ErrMissingParameter = errors.New("missing required parameter")

	// ErrInvalidParameter is returned when a route parameter has an invalid value
	ErrInvalidParameter = errors.New("invalid parameter value")

	// ErrInvalidMiddleware is returned when an invalid middleware type is provided
	ErrInvalidMiddleware = errors.New("invalid middleware type")

	// ErrWildcardConflict is returned when two wildcard routes conflict
	ErrWildcardConflict = errors.New("wildcard route conflicts with existing route")

	// ErrEmptyParameterName is returned when a route parameter name is empty
	ErrEmptyParameterName = errors.New("route parameter name cannot be empty")

	// ErrDuplicateWildcard is returned when multiple wildcards exist in a path segment
	ErrDuplicateWildcard = errors.New("only one wildcard per path segment is allowed")

	// ErrWildcardNotAtEnd is returned when a wildcard is not at the end of the path
	ErrWildcardNotAtEnd = errors.New("catch-all routes are only allowed at the end of the path")

	// ErrInvalidParameterName is returned when a parameter name contains invalid characters
	ErrInvalidParameterName = errors.New("parameter name cannot contain wildcards or other parameters")
)

Common error variables for standardized error handling

View Source
var (
	ErrInvalidHandler = errors.New("invalid handler")
	ErrInvalidMethod  = errors.New("method must not be empty")
	ErrInvalidPath    = errors.New("path must begin with '/'")
	ErrHandlerIsNil   = errors.New("handle must not be nil")
)
View Source
var BodyBytesKey = bodyBytesKey{}

BodyBytesKey indicates a default body bytes key.

View Source
var ContextKey = chainContextKey{}

ContextKey is the request context key under which URL params are stored.

View Source
var EnableDecoderDisallowUnknownFields = false

EnableDecoderDisallowUnknownFields is used to call the DisallowUnknownFields method on the JSON Decoder instance. DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination.

View Source
var EnableDecoderUseNumber = false

EnableDecoderUseNumber is used to call the UseNumber method on the JSON Decoder instance. UseNumber causes the Decoder to unmarshal a number into an any as a Number instead of as a float64.

View Source
var ErrAlreadySent = errors.New("the response was already sent")

ErrAlreadySent Error raised when trying to modify or send an already sent response

View Source
var (
	ErrInvalidNodeName = errors.New("incorrect FQDN node name (example: node@localhost)")
)
View Source
var UnixEpoch = time.Unix(0, 0)

Functions

func Crypto

func Crypto() crypto.Crypto

Crypto get the reference to a structure that has shortcut to all encryption related functions

func GracefulMiddleware added in v1.0.12

func GracefulMiddleware(server *Server) func(ctx *Context, next func() error) error

GracefulMiddleware is a middleware that checks if the server is shutting down. If shutting down, it sets the "Connection: close" header to prevent new connections from being kept alive.

func HashCrc32

func HashCrc32(content []byte) string

func HashMD5 deprecated

func HashMD5(text string) string

HashMD5 computes the MD5 checksum of a string and returns it as a hex-encoded string.

Deprecated: MD5 is cryptographically broken and should not be used for security purposes. MD5 is vulnerable to collision attacks (see https://en.wikipedia.org/wiki/MD5#Security).

For security-sensitive applications, use:

  • HashXxh64 for fast, non-cryptographic checksums
  • crypto.SHA256 or crypto.SHA3 for cryptographic hashing

This function is kept for backward compatibility only.

func HashXxh64 added in v1.0.3

func HashXxh64(content []byte) string

Xxh64 return a base64-encoded checksum of a resource using Xxh64 algorithm

Encoded using Base64 URLSafe

func MapFormWithTag added in v1.0.3

func MapFormWithTag(ptr any, form map[string][]string, tag string) error

func NewKeyring

func NewKeyring(salt string, iterations int, length int, digest string) *crypto.Keyring

NewKeyring starts a Keyring that will be updated whenever SecretKeySync() is invoked

  • `salt` - a salt used with SecretKeyBase to generate a secret
  • `iterations` - defaults to 216,000 (2^16, OWASP recommended minimum for PBKDF2-SHA256)
  • `length` - a length in octets for the derived key. Defaults to 32
  • `digest` - a hmac function to use as the pseudo-random function. Defaults to `sha256`

Security Note: The default of 216,000 iterations follows OWASP 2023 guidelines. For password hashing, consider using Argon2 instead for better security.

func NewUID

func NewUID() (uid string)

func NodeName

func NodeName() string

func SanitizeHeaderValue added in v1.0.12

func SanitizeHeaderValue(value string) string

SanitizeHeaderValue removes potentially dangerous characters from header values

func SanitizePath added in v1.0.12

func SanitizePath(path string) string

SanitizePath cleans a URL path and removes potentially dangerous characters

func SecretKeyBase

func SecretKeyBase() string

SecretKeyBase A secret key used to verify and encrypt data.

This data must be never used directly, always use chain.Crypto().KeyGenerate() to derive keys from it

func SecretKeySync

func SecretKeySync(sync SecretKeySyncFunc) (cancel func())

SecretKeySync is used to transmit SecretKeyBase changes

func SecretKeys

func SecretKeys() []string

SecretKeys gets the list of all SecretKeyBase that have been defined. Can be used in key rotation algorithms

The LAST item in the list is the most recent key (primary key)

func SetNodeName

func SetNodeName(name string) error

func SetSecretKeyBase

func SetSecretKeyBase(secret string) error

SetSecretKeyBase see SecretKeyBase()

func ValidateHeaderValue added in v1.0.12

func ValidateHeaderValue(name string, value string, maxLength int) error

ValidateHeaderValue validates a header value

func ValidateQueryParameter added in v1.0.12

func ValidateQueryParameter(name string, value string, maxLength int) error

ValidateQueryParameter validates a query parameter value

func ValidateRequestBodySize added in v1.0.12

func ValidateRequestBodySize(contentLength int64, maxSize int64) error

ValidateRequestBodySize validates the request body size

func ValidateRouteHandler added in v1.0.12

func ValidateRouteHandler(handler any) error

ValidateRouteHandler validates a route handler and returns an error if invalid

func ValidateRouteMethod added in v1.0.12

func ValidateRouteMethod(method string) error

ValidateRouteMethod validates a route method and returns an error if invalid

func ValidateRoutePath added in v1.0.12

func ValidateRoutePath(path string) error

ValidateRoutePath validates a route path and returns an error if invalid

Types

type BindUnmarshaler added in v1.0.3

type BindUnmarshaler interface {
	// UnmarshalParam decodes and assigns a value from an form or query param.
	UnmarshalParam(param string) error
}

BindUnmarshaler is the interface used to wrap the UnmarshalParam method.

type Binding added in v1.0.3

type Binding interface {
	Bind(*Context, any) error
}

Binding describes the interface which needs to be implemented for binding the data present in the request such as JSON request body, query parameters or the form POST.

var (
	BindingXML           Binding = xmlBinding{}            // xml
	BindingJSON          Binding = jsonBinding{}           // json
	BindingPath          Binding = pathBinding{}           // path
	BindingForm          Binding = formBinding{}           // form
	BindingFormPost      Binding = formPostBinding{}       // form
	BindingFormMultipart Binding = formMultipartBinding{}  // form
	BindingQuery         Binding = queryBinding{}          // query
	BindingHeader        Binding = headerBinding{}         // header
	BindingDefault       Binding = &BindingDefaultStruct{} // query, json, xml, form
)

These implement the Binding interface and can be used to bind the data present in the request to struct instances.

type BindingDefaultStruct added in v1.0.3

type BindingDefaultStruct struct {
	BindHeader bool
}

func (*BindingDefaultStruct) Bind added in v1.0.3

func (s *BindingDefaultStruct) Bind(ctx *Context, obj any) error

type Context

type Context struct {
	Route   *RouteInfo
	Writer  http.ResponseWriter
	Request *http.Request
	Crypto  *cryptoImpl
	// contains filtered or unexported fields
}

Context represents a request & response Context.

func GetContext

func GetContext(ctx context.Context) *Context

GetContext pulls the URL parameters from a request context, or returns nil if none are present.

func (*Context) AddHeader

func (ctx *Context) AddHeader(key, value string)

AddHeader adds the key, value pair to the header. It appends to any existing values associated with key. The key is case insensitive; it is canonicalized by CanonicalHeaderKey.

func (*Context) AfterSend

func (ctx *Context) AfterSend(callback func()) error

func (*Context) BadRequest added in v1.0.3

func (ctx *Context) BadRequest(v ...any)

BadRequest replies to the request with an HTTP 400 bad request error.

func (*Context) BeforeSend

func (ctx *Context) BeforeSend(callback func()) error

BeforeSend Registers a callback to be invoked before the response is sent.

Callbacks are invoked in the reverse order they are defined (callbacks defined first are invoked last).

func (*Context) Bind added in v1.0.3

func (ctx *Context) Bind(obj any) error

Bind checks the Method and Content-Type to select a binding engine automatically, Depending on the "Content-Type" header different bindings are used, for example:

"application/json" --> JSON binding
"application/xml"  --> XML binding

It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. It decodes the json payload into the struct specified as a pointer. It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid.

func (*Context) BindForm added in v1.0.3

func (ctx *Context) BindForm(obj any) error

BindForm is a shortcut for c.MustBindWith(obj, BindingForm).

func (*Context) BindFormMultipart added in v1.0.3

func (ctx *Context) BindFormMultipart(obj any) error

BindFormMultipart is a shortcut for c.MustBindWith(obj, BindingFormMultipart).

func (*Context) BindFormPost added in v1.0.3

func (ctx *Context) BindFormPost(obj any) error

BindFormPost is a shortcut for c.MustBindWith(obj, BindingFormPost).

func (*Context) BindHeader added in v1.0.3

func (ctx *Context) BindHeader(obj any) error

BindHeader is a shortcut for c.MustBindWith(obj, BindingHeader).

func (*Context) BindJSON added in v1.0.3

func (ctx *Context) BindJSON(obj any) error

BindJSON is a shortcut for c.MustBindWith(obj, BindingJSON).

func (*Context) BindPath added in v1.0.3

func (ctx *Context) BindPath(obj any) error

BindPath is a shortcut for c.MustBindWith(obj, BindingPath).

func (*Context) BindQuery added in v1.0.3

func (ctx *Context) BindQuery(obj any) error

BindQuery is a shortcut for c.MustBindWith(obj, BindingQuery).

func (*Context) BindXML added in v1.0.3

func (ctx *Context) BindXML(obj any) error

BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML).

func (*Context) BodyBytes added in v1.0.3

func (ctx *Context) BodyBytes() (body []byte, err error)

BodyBytes get body as array of bytes. It respects the MaxBodySize limit if set on the context.

func (*Context) Child added in v1.0.4

func (ctx *Context) Child() *Context

func (*Context) ContentType added in v1.0.3

func (ctx *Context) ContentType(ctype string)

ContentType set the response content type

func (*Context) Created added in v1.0.3

func (ctx *Context) Created(v ...any)

Created sends an HTTP response header with the 201 Created status code.

func (*Context) Deadline added in v1.0.12

func (ctx *Context) Deadline() (deadline time.Time, ok bool)

Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set.

func (*Context) Destroy added in v1.0.4

func (ctx *Context) Destroy()

func (*Context) Done added in v1.0.12

func (ctx *Context) Done() <-chan struct{}

Done returns a channel that's closed when work done on behalf of this context should be canceled. Done may return nil if this context can never be canceled.

func (*Context) Err added in v1.0.12

func (ctx *Context) Err() error

Err returns an error if the context has been canceled or timed out. Err returns nil if the context is not done.

func (*Context) Error

func (ctx *Context) Error(msg string, code int, v ...any)

Error replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to w. The error message should be plain text.

func (*Context) Forbidden added in v1.0.3

func (ctx *Context) Forbidden(v ...any)

Unauthorized replies to the request with an HTTP 403 Forbidden error.

func (*Context) Get

func (ctx *Context) Get(key any) (any, bool)

Get obtém um valor compartilhado no contexto de execução da requisição

func (*Context) GetContentType added in v1.0.3

func (ctx *Context) GetContentType() string

GetContentType returns the Content-Type header of the request.

func (*Context) GetCookie

func (ctx *Context) GetCookie(name string) *http.Cookie

GetCookie returns the named cookie provided in the request or nil if not found. If multiple cookies match the given name, only one cookie will be returned.

func (*Context) GetHeader

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

GetHeader gets the first value associated with the given key from the request headers. If there are no values associated with the key, GetHeader returns "". It is case-insensitive; http.CanonicalHeaderKey is used to canonicalize the provided key.

Example:

contentType := ctx.GetHeader("Content-Type")
// Returns: "application/json"

func (*Context) GetHeaderValidated added in v1.0.12

func (ctx *Context) GetHeaderValidated(key string, maxLength int) (string, error)

GetHeaderValidated gets a header value with validation for size and format

func (*Context) GetParam

func (ctx *Context) GetParam(name string) string

GetParam returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

func (*Context) GetParamByIndex

func (ctx *Context) GetParamByIndex(index int) string

GetParamByIndex get one parameter per index

func (*Context) GetStatus added in v1.0.4

func (ctx *Context) GetStatus() int

func (*Context) Header

func (ctx *Context) Header() http.Header

Header returns the header map that will be sent by WriteHeader. The Header map also is the mechanism with which Handlers can set HTTP trailers.

Changing the header map after a call to WriteHeader (or Write) has no effect unless the HTTP status code was of the 1xx class or the modified headers are trailers.

There are two ways to set Trailers. The preferred way is to predeclare in the headers which trailers you will later send by setting the "Trailer" header to the names of the trailer keys which will come later. In this case, those keys of the Header map are treated as if they were trailers. See the example. The second way, for trailer keys not known to the Handle until after the first Write, is to prefix the Header map keys with the TrailerPrefix constant value. See TrailerPrefix.

To suppress automatic response headers (such as "Date"), set their value to nil.

func (*Context) Host added in v1.0.3

func (ctx *Context) Host() string

Host host as string

func (*Context) InternalServerError added in v1.0.3

func (ctx *Context) InternalServerError(v ...any)

InternalServerError replies to the request with an HTTP 500 Internal Server Error error.

func (*Context) Ip added in v1.0.3

func (ctx *Context) Ip() string

Host ip as string

func (*Context) Json added in v1.0.3

func (ctx *Context) Json(v any)

Json encode and writes the data to the connection as part of an HTTP reply.

The Content-Length and Content-Type headers are added automatically.

func (*Context) Method added in v1.0.3

func (ctx *Context) Method() string

Method specifies the HTTP method (GET, POST, PUT, etc.).

func (*Context) MustBindWith added in v1.0.3

func (ctx *Context) MustBindWith(obj any, b Binding) error

MustBindWith binds the passed struct pointer using the specified binding engine. It will abort the request with HTTP 400 if any error occurs. See the binding package.

func (*Context) NewUID

func (ctx *Context) NewUID() (uid string)

NewUID get a new KSUID.

KSUID is for K-Sortable Unique IDentifier. It is a kind of globally unique identifier similar to a RFC 4122 UUID, built from the ground-up to be "naturally" sorted by generation timestamp without any special type-aware logic.

See: https://github.com/segmentio/ksuid

func (*Context) NoContent added in v1.0.3

func (ctx *Context) NoContent()

Created sends an HTTP response header with the 204 No Content status code.

func (*Context) NotFound

func (ctx *Context) NotFound(v ...any)

NotFound replies to the request with an HTTP 404 not found error.

func (*Context) NotImplemented added in v1.0.3

func (ctx *Context) NotImplemented(v ...any)

NotImplemented replies to the request with an HTTP 501 Not Implemented error.

func (*Context) OK added in v1.0.3

func (ctx *Context) OK(v ...any)

Created sends an HTTP response header with the 200 OK status code.

func (*Context) QueryParam added in v1.0.3

func (ctx *Context) QueryParam(name string, defaultValue ...string) string

@TODO: cache

func (*Context) QueryParamInt added in v1.0.3

func (ctx *Context) QueryParamInt(name string, defaultValue ...int) int

func (*Context) QueryParamValidated added in v1.0.12

func (ctx *Context) QueryParamValidated(name string, maxLength int) (string, error)

QueryParamValidated returns a validated query parameter with length checking

func (*Context) Redirect

func (ctx *Context) Redirect(url string, code int)

Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.

If the Content-Type header has not been set, Redirect sets it to "text/html; charset=utf-8" and writes a small HTML body.

Setting the Content-Type header to any value, including nil, disables that behavior.

func (*Context) RemoveCookie added in v1.0.3

func (ctx *Context) RemoveCookie(name string)

RemoveCookie delete a cookie by name

func (*Context) ReplaceRequest added in v1.0.12

func (ctx *Context) ReplaceRequest(r *http.Request)

func (*Context) ReplaceWriter added in v1.0.12

func (ctx *Context) ReplaceWriter(w http.ResponseWriter)

func (*Context) Router

func (ctx *Context) Router() *Router

Router get current router reference

func (*Context) ServeContent added in v1.0.3

func (ctx *Context) ServeContent(content []byte, name string, modtime time.Time)

ServeContent replies to the request using the content in the provided. The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests.

If the response's Content-Type header is not set, ServeContent first tries to deduce the type from name's file extension and, if that fails, falls back to reading the first block of the content and passing it to DetectContentType. The name is otherwise unused; in particular it can be empty and is never sent in the response.

If modtime is not the zero time or Unix epoch, ServeContent includes it in a Last-Modified header in the response. If the request includes an If-Modified-Since header, ServeContent uses modtime to decide whether the content needs to be sent at all.

The content's Seek method must work: ServeContent uses a seek to the end of the content to determine its size.

If the caller has set w's ETag header formatted per RFC 7232, section 2.3, ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.

func (*Context) ServiceUnavailable added in v1.0.3

func (ctx *Context) ServiceUnavailable(v ...any)

ServiceUnavailable replies to the request with an HTTP 503 Service Unavailable error.

func (*Context) Set

func (ctx *Context) Set(key any, value any)

Set define um valor compartilhado no contexto de execução da requisição

func (*Context) SetCookie

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

SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func (*Context) SetHeader

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

SetHeader sets the header entries associated with key to the single element value. It replaces any existing values associated with key. The key is case insensitive; it is canonicalized by textproto.CanonicalMIMEHeaderKey. To use non-canonical keys, assign to the map directly.

func (*Context) SetMaxBodySize added in v1.0.12

func (ctx *Context) SetMaxBodySize(size int64)

SetMaxBodySize sets the maximum request body size for this context

func (*Context) ShouldBind added in v1.0.3

func (ctx *Context) ShouldBind(obj any) error

ShouldBind checks the Method and Content-Type to select a binding engine automatically, Depending on the "Content-Type" header different bindings are used, for example:

"application/json" --> JSON binding
"application/xml"  --> XML binding

It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. It decodes the json payload into the struct specified as a pointer. Like c.Bind() but this method does not set the response status code to 400 or abort if input is not valid.

func (*Context) ShouldBindForm added in v1.0.3

func (ctx *Context) ShouldBindForm(obj any) error

ShouldBindForm is a shortcut for c.ShouldBindWith(obj, BindingForm).

func (*Context) ShouldBindFormMultipart added in v1.0.3

func (ctx *Context) ShouldBindFormMultipart(obj any) error

ShouldBindFormMultipart is a shortcut for c.ShouldBindWith(obj, BindingFormMultipart).

func (*Context) ShouldBindFormPost added in v1.0.3

func (ctx *Context) ShouldBindFormPost(obj any) error

ShouldBindFormPost is a shortcut for c.ShouldBindWith(obj, BindingFormPost).

func (*Context) ShouldBindHeader added in v1.0.3

func (ctx *Context) ShouldBindHeader(obj any) error

ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, BindingHeader).

func (*Context) ShouldBindJSON added in v1.0.3

func (c *Context) ShouldBindJSON(obj any) error

ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, BindingJSON).

func (*Context) ShouldBindPath added in v1.0.3

func (ctx *Context) ShouldBindPath(obj any) error

ShouldBindPath is a shortcut for c.ShouldBindWith(obj, BindingPath).

func (*Context) ShouldBindQuery added in v1.0.3

func (ctx *Context) ShouldBindQuery(obj any) error

ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, BindingQuery).

func (*Context) ShouldBindWith added in v1.0.3

func (ctx *Context) ShouldBindWith(obj any, b Binding) error

ShouldBindWith binds the passed struct pointer using the specified binding engine. See the binding package.

func (*Context) ShouldBindXML added in v1.0.3

func (c *Context) ShouldBindXML(obj any) error

ShouldBindXML is a shortcut for c.ShouldBindWith(obj, BindingXML).

func (*Context) Status added in v1.0.3

func (ctx *Context) Status(code int, v ...any)

WriteHeader sends an HTTP response header with the provided status code.

func (*Context) TooManyRequests added in v1.0.3

func (ctx *Context) TooManyRequests(v ...any)

TooManyRequests replies to the request with an HTTP 429 Too Many Requests error.

func (*Context) URL added in v1.0.3

func (ctx *Context) URL() *url.URL

URL request url

func (*Context) Unauthorized added in v1.0.3

func (ctx *Context) Unauthorized(v ...any)

Unauthorized replies to the request with an HTTP 401 Unauthorized error.

func (*Context) UserAgent added in v1.0.3

func (ctx *Context) UserAgent() string

UserAgent returns the client's User-Agent, if sent in the request.

func (*Context) WithParams

func (ctx *Context) WithParams(names []string, values []string) *Context

func (*Context) Write

func (ctx *Context) Write(data []byte) (int, error)

Write writes the data to the connection as part of an HTTP reply.

If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data. If the Header does not contain a Content-Type line, Write adds a Content-Type set to the result of passing the initial 512 bytes of written data to DetectContentType. Additionally, if the total size of all written data is under a few KB and there are no Flush calls, the Content-Length header is added automatically.

Depending on the HTTP protocol version and the client, calling Write or WriteHeader may prevent future reads on the Request.Body. For HTTP/1.x requests, handlers should read any needed request body data before writing the response. Once the headers have been flushed (due to either an explicit Flusher.Flush call or writing enough data to trigger a flush), the request body may be unavailable. For HTTP/2 requests, the Go HTTP server permits handlers to continue to read the request body while concurrently writing the response. However, such behavior may not be supported by all HTTP/2 clients. Handlers should read before writing if possible to maximize compatibility.

func (*Context) WriteCalled added in v1.0.3

func (ctx *Context) WriteCalled() bool

WriteCalled returns true if the ctx.Writer.Write method was called

func (*Context) WriteHeader

func (ctx *Context) WriteHeader(statusCode int)

WriteHeader sends an HTTP response header with the provided status code.

If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes or 1xx informational responses.

The provided code must be a valid HTTP 1xx-5xx status code. Any number of 1xx headers may be written, followed by at most one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx headers may be buffered. Use the Flusher interface to send buffered data. The header map is cleared when 2xx-5xx headers are sent, but not with 1xx headers.

The server will automatically send a 100 (Continue) header on the first read from the request body if the request has an "Expect: 100-continue" header.

func (*Context) WriteHeaderCalled added in v1.0.3

func (ctx *Context) WriteHeaderCalled() bool

WriteCalled returns true if the ctx.Writer.WriteHeader method was called

func (*Context) WriteStarted added in v1.0.3

func (ctx *Context) WriteStarted() bool

WriteStarted returns true if the ctx.Writer.Write or ctx.Writer.WriteHeader method was called

type Group

type Group interface {
	GET(route string, handle any) error
	HEAD(route string, handle any) error
	OPTIONS(route string, handle any) error
	POST(route string, handle any) error
	PUT(route string, handle any) error
	PATCH(route string, handle any) error
	DELETE(route string, handle any) error
	Use(args ...any) (Group, error)
	Group(route string) Group
	Handle(method string, route string, handle any) error
	Configure(route string, configurator RouteConfigurator)
}

type Handle

type Handle func(*Context) error

func Handler added in v1.0.3

func Handler(handle any) (h Handle, err error)

Handle registers a new Route for the given method and path.

type JsonSerializer

type JsonSerializer struct {
}

func (*JsonSerializer) Decode

func (s *JsonSerializer) Decode(data []byte, v any) (any, error)

func (*JsonSerializer) Encode

func (s *JsonSerializer) Encode(v any) ([]byte, error)

type Middleware

type Middleware struct {
	Path   *RouteInfo
	Handle func(ctx *Context, next func() error) error
}

type MiddlewareChain added in v1.0.12

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

MiddlewareChain is a helper type that manages a chain of middleware functions

func NewMiddlewareChain added in v1.0.12

func NewMiddlewareChain(middlewares ...MiddlewareFunc) *MiddlewareChain

NewMiddlewareChain creates a new middleware chain

func (*MiddlewareChain) Add added in v1.0.12

func (mc *MiddlewareChain) Add(middleware MiddlewareFunc)

Add appends middleware to the chain

func (*MiddlewareChain) Execute added in v1.0.12

func (mc *MiddlewareChain) Execute(ctx *Context, handler func() error) error

Execute runs the middleware chain with the given handler

type MiddlewareFunc added in v1.0.12

type MiddlewareFunc func(ctx *Context, next func() error) error

MiddlewareFunc is the standard middleware function signature

func ContentTypeMiddleware added in v1.0.12

func ContentTypeMiddleware(allowedTypes ...string) MiddlewareFunc

ContentTypeMiddleware creates middleware that validates Content-Type header

func MaxBytesMiddleware added in v1.0.12

func MaxBytesMiddleware(maxSize int64) MiddlewareFunc

MaxBytesMiddleware creates middleware that limits request body size

func WrapHandler added in v1.0.12

func WrapHandler(handler http.Handler) MiddlewareFunc

WrapHandler wraps an http.Handler with middleware chain

type MiddlewareHandler

type MiddlewareHandler interface {
	Handle(ctx *Context, next func() error) error
}

type MiddlewareWithInitHandler

type MiddlewareWithInitHandler interface {
	Init(method string, path string, router *Router)
	Handle(ctx *Context, next func() error) error
}

type Registry

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

Registry is an algorithm-independent framework for recording routes. This division allows us to explore different algorithms without breaking the contract.

type ResponseWriterSpy

type ResponseWriterSpy struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

func (*ResponseWriterSpy) Status added in v1.0.4

func (w *ResponseWriterSpy) Status() int

func (*ResponseWriterSpy) Write

func (w *ResponseWriterSpy) Write(b []byte) (int, error)

func (*ResponseWriterSpy) WriteHeader

func (w *ResponseWriterSpy) WriteHeader(status int)

type Route

type Route struct {
	Info        *RouteInfo
	Handle      Handle
	Middlewares []*Middleware
	// contains filtered or unexported fields
}

Route control of a registered route

func (*Route) Dispatch

func (r *Route) Dispatch(ctx *Context) error

Dispatch ctx into this route

type RouteConfigurator

type RouteConfigurator interface {
	Configure(router *Router, path string)
}

type RouteInfo added in v1.0.4

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

RouteInfo represents all useful information about a dynamic path (used by handlers)

func ParseRouteInfo added in v1.0.4

func ParseRouteInfo(pathOrig string) (*RouteInfo, error)

ParseRouteInfo obtém informações sobre um path dinamico. Returns an error if the path contains invalid route syntax.

func (*RouteInfo) Details added in v1.0.4

func (d *RouteInfo) Details() (segments []string, params []string, indexes []int)

func (*RouteInfo) FastMatch added in v1.0.4

func (d *RouteInfo) FastMatch(ctx *Context) bool

func (*RouteInfo) HasParameter added in v1.0.4

func (d *RouteInfo) HasParameter() bool

func (*RouteInfo) HasStatic added in v1.0.4

func (d *RouteInfo) HasStatic() bool

func (*RouteInfo) HasWildcard added in v1.0.4

func (d *RouteInfo) HasWildcard() bool

func (RouteInfo) Match added in v1.0.4

func (d RouteInfo) Match(ctx *Context) (match bool, paramNames []string, paramValues []string)

Match checks if the patch is compatible, performs the extraction of parameters

func (*RouteInfo) Matches added in v1.0.4

func (d *RouteInfo) Matches(o *RouteInfo) bool

Matches checks if this path is applicable over the other. Used for registering middlewares in routes

func (*RouteInfo) Params added in v1.0.4

func (d *RouteInfo) Params() []string

func (*RouteInfo) ParamsIndex added in v1.0.4

func (d *RouteInfo) ParamsIndex() []int

func (*RouteInfo) Path added in v1.0.4

func (d *RouteInfo) Path() string

func (*RouteInfo) Pattern added in v1.0.4

func (d *RouteInfo) Pattern() string

func (*RouteInfo) Priority added in v1.0.4

func (d *RouteInfo) Priority() int

func (*RouteInfo) ReplacePath added in v1.0.4

func (d *RouteInfo) ReplacePath(ctx *Context) string

func (*RouteInfo) Segments added in v1.0.4

func (d *RouteInfo) Segments() []string

func (*RouteInfo) String added in v1.0.4

func (d *RouteInfo) String() string

type RouteStorage

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

type RouteValidationError added in v1.0.12

type RouteValidationError struct {
	// Field is the field that failed validation
	Field string
	// Value is the invalid value
	Value string
	// Message is a human-readable error message
	Message string
}

RouteValidationError represents a validation error for route configuration

func NewRouteValidationError added in v1.0.12

func NewRouteValidationError(field string, value string, message string) *RouteValidationError

NewRouteValidationError creates a new RouteValidationError

func (*RouteValidationError) Error added in v1.0.12

func (e *RouteValidationError) Error() string

func (*RouteValidationError) Is added in v1.0.12

func (e *RouteValidationError) Is(target error) bool

Is implements errors.Is for RouteValidationError

type Router

type Router struct {
	Crypto cryptoImpl

	// ReqContext optionally specifies a function that modifies
	// the context used for the request.
	ReqContext func(*Context) context.Context

	// If enabled, the router automatically replies to OPTIONS requests.
	// Custom OPTIONS handlers take priority over automatic replies.
	HandleOPTIONS bool

	// If enabled, the router tries to fix the current request path, if no handle is registered for it.
	// First superfluous path elements like ../ or // are removed.
	// Afterwards the router does a case-insensitive lookup of the cleaned path.
	// If a handle can be found for this route, the router makes a redirection to the corrected path with status code
	// 301 for GET requests and 308 for all other request methods.
	// For example /FOO and /..//Foo could be redirected to /foo.
	// RedirectTrailingSlash is independent of this option.
	RedirectFixedPath bool

	// Enables automatic redirection if the current route can't be matched but a handler for the path with (without)
	// the trailing slash exists.
	// For example if /foo/ is requested but a route only exists for /foo, the client is redirected to /foo with http
	// status code 301 for GET requests and 308 for all other request methods.
	RedirectTrailingSlash bool

	// If enabled, the router checks if another method is allowed for the current route, if the current request can not
	// be routed.
	// If this is the case, the request is answered with 'Method Not Allowed' and HTTP status code 405.
	// If no other Method is allowed, the request is delegated to the NotFoundHandler handler.
	HandleMethodNotAllowed bool

	// Function to handle panics recovered from http handlers.
	// It should be used to generate a error page and return the http error code 500 (Internal Server Error).
	// The handler can be used to keep your server from crashing because of unrecovered panics.
	PanicHandler func(http.ResponseWriter, *http.Request, any)

	// Function to handle errors recovered from http handlers and middlewares.
	// The handler can be used to do global error handling (not handled in middlewares)
	ErrorHandler func(*Context, error)

	// Configurable http.Handler function which is called when no matching route is found. If it is not set, http.NotFound is
	// used.
	NotFoundHandler http.Handler

	// An optional http.Handler function that is called on automatic OPTIONS requests.
	// The handler is only called if HandleOPTIONS is true and no OPTIONS handler for the specific path was set.
	// The "Allowed" header is set before calling the handler.
	GlobalOPTIONSHandler http.Handler

	// Configurable http.Handler function which is called when a request cannot be routed and HandleMethodNotAllowed is true.
	// If it is not set, http.Error with http.StatusMethodNotAllowed is used.
	// The "Allow" header with allowed request methods is set before the handler is called.
	MethodNotAllowedHandler http.Handler
	// contains filtered or unexported fields
}

Router is a high-performance router.

func New

func New() *Router

func (*Router) Configure

func (r *Router) Configure(route string, configurator RouteConfigurator)

Configure allows a RouteConfigurator to perform route configurations

func (*Router) DELETE

func (r *Router) DELETE(route string, handle any) error

DELETE is a shortcut for router.handleFunc(http.MethodDelete, Route, handle)

func (*Router) GET

func (r *Router) GET(route string, handle any) error

GET is a shortcut for router.handleFunc(http.MethodGet, Route, handle)

func (*Router) Group

func (r *Router) Group(route string) Group

func (*Router) HEAD

func (r *Router) HEAD(route string, handle any) error

HEAD is a shortcut for router.handleFunc(http.MethodHead, Route, handle)

func (*Router) Handle

func (r *Router) Handle(method string, route string, handle any) error

Handle registers a new Route for the given method and path.

func (*Router) Lookup

func (r *Router) Lookup(method string, path string) (*Route, *Context)

Lookup finds the Route and parameters for the given Route and assigns them to the given Context.

func (*Router) OPTIONS

func (r *Router) OPTIONS(route string, handle any) error

OPTIONS is a shortcut for router.handleFunc(http.MethodOptions, Route, handle)

func (*Router) PATCH

func (r *Router) PATCH(route string, handle any) error

PATCH is a shortcut for router.handleFunc(http.MethodPatch, Route, handle)

func (*Router) POST

func (r *Router) POST(route string, handle any) error

POST is a shortcut for router.handleFunc(http.MethodPost, Route, handle)

func (*Router) PUT

func (r *Router) PUT(route string, handle any) error

PUT is a shortcut for router.handleFunc(http.MethodPut, Route, handle)

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP responds to the given request.

func (*Router) Use

func (r *Router) Use(args ...any) (Group, error)

Use registers a middleware routeT that will match requests with the provided prefix (which is optional and defaults to "/*").

router.Use(func(ctx *chain.Context) error {
    return ctx.NextFunc()
})

router.Use(firstMiddleware, secondMiddleware)

app.Use("/api", func(ctx *chain.Context) error {
    return ctx.NextFunc()
})

app.Use("GET", "/api", func(ctx *chain.Context) error {
    return ctx.NextFunc()
})

app.Use("GET", "/files/*filepath", func(ctx *chain.Context) error {
    println(ctx.GetParam("filepath"))
    return ctx.NextFunc()
})

type RouterGroup

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

func (*RouterGroup) Configure

func (r *RouterGroup) Configure(route string, configurator RouteConfigurator)

func (*RouterGroup) DELETE

func (r *RouterGroup) DELETE(route string, handle any) error

func (*RouterGroup) GET

func (r *RouterGroup) GET(route string, handle any) error

func (*RouterGroup) Group

func (r *RouterGroup) Group(route string) Group

func (*RouterGroup) HEAD

func (r *RouterGroup) HEAD(route string, handle any) error

func (*RouterGroup) Handle

func (r *RouterGroup) Handle(method string, route string, handle any) error

func (*RouterGroup) OPTIONS

func (r *RouterGroup) OPTIONS(route string, handle any) error

func (*RouterGroup) PATCH

func (r *RouterGroup) PATCH(route string, handle any) error

func (*RouterGroup) POST

func (r *RouterGroup) POST(route string, handle any) error

func (*RouterGroup) PUT

func (r *RouterGroup) PUT(route string, handle any) error

func (*RouterGroup) Use

func (r *RouterGroup) Use(args ...any) (Group, error)

Use registers a middleware routeT that will match requests with the provided prefix (which is optional and defaults to "/*").

group.Use(func(ctx *chain.Context) error {
    return ctx.NextFunc()
})

group.Use(firstMiddleware, secondMiddleware)

group.Use("/api", func(ctx *chain.Context) error {
    return ctx.NextFunc()
})

group.Use("GET", "/api", func(ctx *chain.Context) error {
    return ctx.NextFunc()
})

group.Use("GET", "/files/*filepath", func(ctx *chain.Context) error {
    println(ctx.GetParam("filepath"))
    return ctx.NextFunc()
})

type SecretKeySyncFunc

type SecretKeySyncFunc func(key string)

type Serializer

type Serializer interface {
	Encode(v any) ([]byte, error)
	Decode(data []byte, v any) (any, error)
}

type Server added in v1.0.12

type Server struct {
	// Server is the underlying http.Server.
	Server *http.Server

	// Config holds the shutdown configuration.
	Config ShutdownConfig
	// contains filtered or unexported fields
}

Server wraps an http.Server with graceful shutdown support.

Example:

r := chain.New()
r.GET("/", handler)

server := chain.NewServer(r, ":8080")
if err := server.ListenAndServe(); err != nil {
    log.Fatal(err)
}

func NewServer added in v1.0.12

func NewServer(router *Router, addr string) *Server

NewServer creates a new Server with graceful shutdown support. The addr parameter is the same as http.Server.Addr (e.g., ":8080").

Example:

r := chain.New()
server := chain.NewServer(r, ":8080")
server.ListenAndServe()

func NewServerWithConfig added in v1.0.12

func NewServerWithConfig(router *Router, addr string, config ShutdownConfig) *Server

NewServerWithConfig creates a new Server with custom configuration.

Example:

r := chain.New()
server := chain.NewServerWithConfig(r, ":8080", chain.ShutdownConfig{
    Timeout: 60 * time.Second,
})

func (*Server) IsShuttingDown added in v1.0.12

func (s *Server) IsShuttingDown() bool

IsShuttingDown returns true if the server is in the process of shutting down.

func (*Server) ListenAndServe added in v1.0.12

func (s *Server) ListenAndServe() error

ListenAndServe starts the server and blocks until the server is shut down. It listens on the configured address and handles graceful shutdown on OS signals.

Example:

server := chain.NewServer(router, ":8080")
if err := server.ListenAndServe(); err != nil {
    log.Fatal(err)
}

func (*Server) ListenAndServeTLS added in v1.0.12

func (s *Server) ListenAndServeTLS(certFile, keyFile string) error

ListenAndServeTLS starts the server with TLS and blocks until the server is shut down.

Example:

server := chain.NewServer(router, ":8443")
if err := server.ListenAndServeTLS("cert.pem", "key.pem"); err != nil {
    log.Fatal(err)
}

func (*Server) OnShutdown added in v1.0.12

func (s *Server) OnShutdown(fn func())

OnShutdown registers a callback that is called when shutdown begins, before waiting for in-flight requests to complete.

func (*Server) OnStop added in v1.0.12

func (s *Server) OnStop(fn func())

OnStop registers a callback that is called after all in-flight requests have completed or the shutdown timeout is reached.

func (*Server) Shutdown added in v1.0.12

func (s *Server) Shutdown(ctx context.Context) error

Shutdown initiates a graceful shutdown with the provided context. If ctx is nil, a background context with the configured timeout is used.

This method can be called directly for programmatic shutdown:

server.Shutdown(nil)

func (*Server) Stop added in v1.0.12

func (s *Server) Stop() error

Stop signals the server to shut down gracefully. This is useful for triggering shutdown from application code.

func (*Server) Wait added in v1.0.12

func (s *Server) Wait()

Wait blocks until the server has fully shut down. This is useful for coordinating cleanup after shutdown.

type ShutdownConfig added in v1.0.12

type ShutdownConfig struct {
	// Timeout is the maximum duration to wait for in-flight requests
	// to complete before forcefully shutting down.
	// If zero, a default of 30 seconds is used.
	Timeout time.Duration

	// Signals specifies which OS signals trigger graceful shutdown.
	// If nil, defaults to []os.Signal{syscall.SIGINT, syscall.SIGTERM}.
	Signals []os.Signal
}

ShutdownConfig holds configuration for graceful shutdown behavior.

type SliceValidationErrors added in v1.0.12

type SliceValidationErrors []error

func (SliceValidationErrors) Error added in v1.0.12

func (err SliceValidationErrors) Error() string

Error concatenates all error elements in SliceValidationError into a single string separated by \n.

type StructValidator added in v1.0.3

type StructValidator interface {
	// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.
	// If the received type is a slice|array, the validation should be performed travel on every element.
	// If the received type is not a struct or slice|array, any validation should be skipped and nil must be returned.
	// If the received type is a struct or pointer to a struct, the validation should be performed.
	// If the struct is not valid or the validation itself fails, a descriptive error should be returned.
	// Otherwise nil must be returned.
	ValidateStruct(any) error

	// Engine returns the underlying validator engine which powers the
	// StructValidator implementation.
	Engine() any
}

StructValidator is the minimal interface which needs to be implemented in order for it to be used as the validator engine for ensuring the correctness of the request. Gin provides a default implementation for this using https://github.com/go-playground/validator/tree/v10.6.1.

var Validator StructValidator = &defaultValidator{}

Validator is the default validator which implements the StructValidator interface. It uses https://github.com/go-playground/validator/tree/v10.6.1 under the hood.

Directories

Path Synopsis
examples
basic-server command
Package main demonstrates a basic Chain HTTP server.
Package main demonstrates a basic Chain HTTP server.
crypto command
crypto-basics command
Package main demonstrates cryptographic utilities in Chain.
Package main demonstrates cryptographic utilities in Chain.
data-binding command
Package main demonstrates data binding in Chain.
Package main demonstrates data binding in Chain.
error-handling command
Package main demonstrates error handling in Chain.
Package main demonstrates error handling in Chain.
file-upload command
Package main demonstrates file upload handling in Chain.
Package main demonstrates file upload handling in Chain.
message-signing command
Package main demonstrates message signing and verification in Chain.
Package main demonstrates message signing and verification in Chain.
middleware command
Package main demonstrates middleware patterns in Chain.
Package main demonstrates middleware patterns in Chain.
pubsub command
route-groups command
Package main demonstrates route grouping in Chain.
Package main demonstrates route grouping in Chain.
router command
socket-chat command
socket-cluster command
validation command
Package main demonstrates request validation in Chain.
Package main demonstrates request validation in Chain.
middlewares
logger
Package logger provides structured logging middleware for Chain.
Package logger provides structured logging middleware for Chain.
recovery
Package recovery provides panic recovery middleware for Chain.
Package recovery provides panic recovery middleware for Chain.
timeout
Package timeout provides request timeout middleware for Chain.
Package timeout provides request timeout middleware for Chain.

Jump to

Keyboard shortcuts

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