chain

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2023 License: MIT Imports: 22 Imported by: 0

README


To create distributed systems in a simple, elegant and safe way.


Chain is a core library that tries to provide all the necessary machinery to create distributed systems in a simple, elegant and safe way.

Feature Overview

  • Optimized HTTP Router middleware
  • Realtime Publisher/Subscriber service.
  • Socket & Channels: A socket implementation that multiplexes messages over channels.
  • Crypto-related functionalities

Installation

go get github.com/nidorx/chain

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

Documentation

Index

Constants

This section is empty.

Variables

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

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

View Source
var ContextKey = chainContextKey{}

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

Functions

func Crypto

func Crypto() *cryptoShortcuts

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

func HashCrc32

func HashCrc32(content []byte) string

func HashMD5

func HashMD5(text string) string

HashMD5 computing the MD5 checksum of strings

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 1000 (increase to at least 2^16 if used for passwords)
  • `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`

func NewUID

func NewUID() (uid string)

func NodeName

func NodeName() string

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)

func SetSecretKeyBase

func SetSecretKeyBase(secret string) error

SetSecretKeyBase see SecretKeyBase()

Types

type Context

type Context struct {
	MatchedRoutePath string
	Writer           http.ResponseWriter
	Request          *http.Request
	Crypto           *cryptoShortcuts
	// 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) 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) DeleteCookie

func (ctx *Context) DeleteCookie(name string)

DeleteCookie delete a cookie by name

func (*Context) Error

func (ctx *Context) Error(error string, code int)

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) Get

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

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

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. If there are no values associated with the key, GetHeader returns "". It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. Get assumes that all keys are stored in canonical form. To use non-canonical keys, access the map directly.

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) 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) 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) NotFound

func (ctx *Context) NotFound()

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

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) Router

func (ctx *Context) Router() *Router

Router get current router reference

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) 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) 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.

type Group

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

type Handle

type Handle func(*Context) error

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   *PathDetails
	Handle func(ctx *Context, next func() error) error
}

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 PathDetails

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

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

func ParsePathDetails

func ParsePathDetails(pathOrig string) *PathDetails

ParsePathDetails obtém informações sobre um path dinamico.

func (PathDetails) FastMatch

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

func (PathDetails) Match

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

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

func (PathDetails) MaybeMatches

func (d PathDetails) MaybeMatches(o *PathDetails) bool

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

func (PathDetails) ReplacePath

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

func (PathDetails) String

func (d PathDetails) String() string

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) Write

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

func (*ResponseWriterSpy) WriteHeader

func (w *ResponseWriterSpy) WriteHeader(status int)

type Route

type Route struct {
	Path        *PathDetails
	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 RouteStorage

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

type Router

type Router struct {
	Crypto cryptoShortcuts

	// 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 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

	// If enabled, the router automatically replies to OPTIONS requests.
	// Custom OPTIONS handlers take priority over automatic replies.
	HandleOPTIONS 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

	// 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

	// 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

	// 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

	// 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)

	// 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)
	// 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)

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

func (*Router) GET

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

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

func (*Router) GetContext

func (r *Router) GetContext(req *http.Request, w http.ResponseWriter, path string) *Context

GetContext returns a new ContextImpl from the pool.

func (*Router) Group

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

func (*Router) HEAD

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

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

func (*Router) Handle

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

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)

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

func (*Router) PATCH

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

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

func (*Router) POST

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

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

func (*Router) PUT

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

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

func (*Router) PutContext

func (r *Router) PutContext(ctx *Context)

PutContext Close frees up resources and is automatically called in the ServeHTTP part of the web server.

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

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)

func (*RouterGroup) GET

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

func (*RouterGroup) Group

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

func (*RouterGroup) HEAD

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

func (*RouterGroup) Handle

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

func (*RouterGroup) OPTIONS

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

func (*RouterGroup) PATCH

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

func (*RouterGroup) POST

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

func (*RouterGroup) PUT

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

func (*RouterGroup) Use

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

type SecretKeySyncFunc

type SecretKeySyncFunc func(key string)

type Serializer

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

Directories

Path Synopsis
examples
middlewares

Jump to

Keyboard shortcuts

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