atreugo

package module
v8.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2019 License: GPL-3.0 Imports: 18 Imported by: 0

README

Atreugo

Build Status Coverage Status Go Report Card GoDoc GitHub release

High performance and extensible micro web framework with zero memory allocations in hot paths.

It's build on top of fasthttp.

Install

go get github.com/savsgio/atreugo/v8

Supported Go versions:

  • 1.9.x
  • 1.10.x
  • 1.11.x
  • 1.12.x

Documentation

See: docs

Feature Overview

  • Optimized for speed. Easily handles more than 100K qps and more than 1M concurrent keep-alive connections on modern hardware.

  • Optimized for low memory usage.

  • Easy 'Connection: Upgrade' support via RequestCtx.Hijack.

  • Server provides anti-DoS limits.

  • Middlewares support:

    • Before view execution.
    • After view execution.
  • Easy routing:

    • Path parameters (mandatories and optionals).
    • Views with timeout.
    • Group paths and middlewares.
    • Static files.
    • Serve one file like pdf, etc.
    • Filters (middlewares) to especific views.
    • net/http handlers support.
    • fasthttp handlers support
  • Common responses (also you could use your own responses):

    • JSON
    • HTTP
    • Text
    • Raw
    • File
    • Redirect

Examples:

Go to examples directory to see how to use Atreugo.

Note:

*atreugo.RequestCtx is equal than *fasthttp.RequestCtx, but adding extra funtionality, so you can use the same functions of *fasthttp.RequestCtx. Don't worry 😄

Benchmark

Best Performance: Atreugo is one of the fastest go web frameworks in the go-web-framework-benchmark.

  • Basic Test: The first test case is to mock 0 ms, 10 ms, 100 ms, 500 ms processing time in handlers.

  • Concurrency Test (allocations): In 30 ms processing time, the tets result for 100, 1000, 5000 clients is:

* Smaller is better

Useful third-party libraries

Contributing

Feel free to contribute it or fork me... 😉

Documentation

Overview

Package atreugo is a high performance and extensible micro web framework with zero memory allocations in hot paths

It's build on top of fasthttp and provides the following features:

  • Optimized for speed. Easily handles more than 100K qps and more than 1M concurrent keep-alive connections on modern hardware.

  • Optimized for low memory usage.

  • Easy 'Connection: Upgrade' support via RequestCtx.Hijack.

  • Server provides the following anti-DoS limits:

  • The number of concurrent connections.

  • The number of concurrent connections per client IP.

  • The number of requests per connection.

  • Request read timeout.

  • Response write timeout.

  • Maximum request header size.

  • Maximum request body size.

  • Maximum request execution time.

  • Maximum keep-alive connection lifetime.

  • Early filtering out non-GET requests.

  • A lot of additional useful info is exposed to request handler:

  • Server and client address.

  • Per-request logger.

  • Unique request id.

  • Request start time.

  • Connection start time.

  • Request sequence number for the current connection.

  • Middlewares support:

  • Before view execution.

  • After view execution.

  • Easy routing:

  • Path parameters (mandatories and optionals).

  • Views with timeout.

  • Group paths and middlewares.

  • Static files.

  • Serve one file like pdf, etc.

  • Filters (middlewares) to especific views.

  • net/http handlers support.

  • fasthttp handlers support

  • Common responses (also you could use your own responses):

  • JSON

  • HTTP

  • Text

  • Raw

  • File

  • Redirect

Index

Constants

View Source
const XRequestIDHeader = "X-Request-ID"

XRequestIDHeader header name of request id

Variables

This section is empty.

Functions

This section is empty.

Types

type Atreugo

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

Atreugo implements high performance HTTP server

It is prohibited copying Atreugo values. Create new values instead.

func New

func New(cfg *Config) *Atreugo

New create a new instance of Atreugo Server

func (*Atreugo) ListenAndServe

func (s *Atreugo) ListenAndServe() error

ListenAndServe serves HTTP/HTTPS requests from the given TCP4 addr in the atreugo configuration.

Pass custom listener to Serve/ServeGracefully if you need listening on non-TCP4 media such as IPv6.

func (*Atreugo) Serve

func (s *Atreugo) Serve(ln net.Listener) error

Serve serves incoming connections from the given listener.

Serve blocks until the given listener returns permanent error.

If use a custom Listener, will be updated your atreugo configuration with the Listener address automatically

func (*Atreugo) ServeGracefully

func (s *Atreugo) ServeGracefully(ln net.Listener) error

ServeGracefully serves incoming connections from the given listener with graceful shutdown

ServeGracefully blocks until the given listener returns permanent error.

If use a custom Listener, will be updated your atreugo configuration with the Listener address and setting GracefulShutdown to true automatically.

func (*Atreugo) SetLogOutput

func (s *Atreugo) SetLogOutput(output io.Writer)

SetLogOutput set log output of server

type Config

type Config struct {
	Host string
	Port int

	// TLS/SSL options
	TLSEnable bool
	CertKey   string
	CertFile  string

	// Server name for sending in response headers. (default: Atreugo)
	Name string

	// Default: atreugo
	LogName string

	// See levels in https://github.com/savsgio/go-logger#levels
	LogLevel string

	// Kind of network listener (default: tcp4)
	// The network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket".
	Network string

	// Compress transparently the response body generated by handler if the request contains 'gzip' or 'deflate'
	// in 'Accept-Encoding' header.
	Compress bool

	// Run server with a TCP listener with SO_REUSEPORT option set.
	// Just supported tcp4 and tcp6, and not with Windows OS.
	//
	// It is recommended to scale linearly, executing several instances (as many as usable logical CPUs)
	// of the same server in different processes, significantly increasing performance.
	//
	//It is IMPORTANT that each of these processes be executed with GOMAXPROCS=1.
	Reuseport bool

	// Shutdown gracefully shuts down the server without interrupting any active connections.
	// Shutdown works by first closing all open listeners and then waiting indefinitely for all connections to return to idle and then shut down.
	GracefulShutdown bool

	// Configurable view which is called when no matching route is
	// found. If it is not set, http.NotFound is used.
	NotFoundView View

	// Configurable view which is called when a request
	// cannot be routed.
	// 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.
	MethodNotAllowedView View

	// Function to handle panics recovered from views.
	// 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.
	PanicView PanicView

	// The maximum number of concurrent connections the server may serve.
	//
	// DefaultConcurrency is used if not set.
	Concurrency int

	// Whether to disable keep-alive connections.
	//
	// The server will close all the incoming connections after sending
	// the first response to client if this option is set to true.
	//
	// By default keep-alive connections are enabled.
	DisableKeepalive bool

	// Per-connection buffer size for requests' reading.
	// This also limits the maximum header size.
	//
	// Increase this buffer if your clients send multi-KB RequestURIs
	// and/or multi-KB headers (for example, BIG cookies).
	//
	// Default buffer size is used if not set.
	ReadBufferSize int

	// Per-connection buffer size for responses' writing.
	//
	// Default buffer size is used if not set.
	WriteBufferSize int

	// ReadTimeout is the amount of time allowed to read
	// the full request including body. The connection's read
	// deadline is reset when the connection opens, or for
	// keep-alive connections after the first byte has been read.
	//
	// By default request read timeout is unlimited.
	ReadTimeout time.Duration

	// WriteTimeout is the maximum duration before timing out
	// writes of the response. It is reset after the request handler
	// has returned.
	//
	// By default response write timeout is unlimited.
	WriteTimeout time.Duration

	// IdleTimeout is the maximum amount of time to wait for the
	// next request when keep-alive is enabled. If IdleTimeout
	// is zero, the value of ReadTimeout is used.
	IdleTimeout time.Duration

	// Maximum number of concurrent client connections allowed per IP.
	//
	// By default unlimited number of concurrent connections
	// may be established to the server from a single IP address.
	MaxConnsPerIP int

	// Maximum number of requests served per connection.
	//
	// The server closes connection after the last request.
	// 'Connection: close' header is added to the last response.
	//
	// By default unlimited number of requests may be served per connection.
	MaxRequestsPerConn int

	// MaxKeepaliveDuration is a no-op and only left here for backwards compatibility.
	// Deprecated: Use IdleTimeout instead.
	MaxKeepaliveDuration time.Duration

	// Maximum request body size.
	//
	// The server rejects requests with bodies exceeding this limit.
	//
	// Request body size is limited by DefaultMaxRequestBodySize by default.
	MaxRequestBodySize int

	// Aggressively reduces memory usage at the cost of higher CPU usage
	// if set to true.
	//
	// Try enabling this option only if the server consumes too much memory
	// serving mostly idle keep-alive connections. This may reduce memory
	// usage by more than 50%.
	//
	// Aggressive memory usage reduction is disabled by default.
	ReduceMemoryUsage bool

	// Rejects all non-GET requests if set to true.
	//
	// This option is useful as anti-DoS protection for servers
	// accepting only GET requests. The request size is limited
	// by ReadBufferSize if GetOnly is set.
	//
	// Server accepts all the requests by default.
	GetOnly bool

	// Logs all errors, including the most frequent
	// 'connection reset by peer', 'broken pipe' and 'connection timeout'
	// errors. Such errors are common in production serving real-world
	// clients.
	//
	// By default the most frequent errors such as
	// 'connection reset by peer', 'broken pipe' and 'connection timeout'
	// are suppressed in order to limit output log traffic.
	LogAllErrors bool

	// Header names are passed as-is without normalization
	// if this option is set.
	//
	// Disabled header names' normalization may be useful only for proxying
	// incoming requests to other servers expecting case-sensitive
	// header names. See https://github.com/valyala/fasthttp/issues/57
	// for details.
	//
	// By default request and response header names are normalized, i.e.
	// The first letter and the first letters following dashes
	// are uppercased, while all the other letters are lowercased.
	// Examples:
	//
	//     * HOST -> Host
	//     * content-type -> Content-Type
	//     * cONTENT-lenGTH -> Content-Length
	DisableHeaderNamesNormalizing bool

	// SleepWhenConcurrencyLimitsExceeded is a duration to be slept of if
	// the concurrency limit in exceeded (default [when is 0]: don't sleep
	// and accept new connections immidiatelly).
	SleepWhenConcurrencyLimitsExceeded time.Duration

	// NoDefaultServerHeader, when set to true, causes the default Server header
	// to be excluded from the Response.
	//
	// The default Server header value is the value of the Name field or an
	// internal default value in its absence. With this option set to true,
	// the only time a Server header will be sent is if a non-zero length
	// value is explicitly provided during a request.
	NoDefaultServerHeader bool

	// NoDefaultContentType, when set to true, causes the default Content-Type
	// header to be excluded from the Response.
	//
	// The default Content-Type header value is the internal default value. When
	// set to true, the Content-Type will not be present.
	NoDefaultContentType bool

	// ConnState specifies an optional callback function that is
	// called when a client connection changes state. See the
	// ConnState type and associated constants for details.
	ConnState func(net.Conn, fasthttp.ConnState)

	// KeepHijackedConns is an opt-in disable of connection
	// close by fasthttp after connections' HijackHandler returns.
	// This allows to save goroutines, e.g. when fasthttp used to upgrade
	// http connections to WS and connection goes to another handler,
	// which will close it when needed.
	KeepHijackedConns bool
}

Config configuration to run server

Default settings should satisfy the majority of Server users. Adjust Server settings only if you really understand the consequences.

type Filters added in v8.1.0

type Filters struct {
	Before []Middleware
	After  []Middleware
}

Filters like middlewares, but for specific paths. It will be executed before and after the view defined in the path in addition of the general middlewares

type JSON

type JSON map[string]interface{}

JSON is a map whose key is a string and whose value an interface

type Middleware

type Middleware func(*RequestCtx) (int, error)

Middleware must process all incoming requests before/after defined views.

type PanicView added in v8.2.0

type PanicView func(*RequestCtx, interface{})

PanicView must process panics recovered from views, if it's defined in configuration.

type PathRewriteFunc added in v8.2.0

type PathRewriteFunc func(ctx *RequestCtx) []byte

PathRewriteFunc must return new request path based on arbitrary ctx info such as ctx.Path().

Path rewriter is used in StaticFS for translating the current request to the local filesystem path relative to StaticFS.Root.

The returned path must not contain '/../' substrings due to security reasons, since such paths may refer files outside StaticFS.Root.

The returned path may refer to ctx members. For example, ctx.Path().

type RequestCtx

type RequestCtx struct {
	*fasthttp.RequestCtx
	// contains filtered or unexported fields
}

RequestCtx context wrapper of fasthttp.RequestCtx to adds extra funtionality

It is prohibited copying RequestCtx values. Create new values instead.

func (*RequestCtx) FileResponse

func (ctx *RequestCtx) FileResponse(fileName, filePath, mimeType string) error

FileResponse return a streaming response with file data.

func (*RequestCtx) HTTPResponse

func (ctx *RequestCtx) HTTPResponse(body string, statusCode ...int) error

HTTPResponse return response with body in html format

func (*RequestCtx) HTTPResponseBytes

func (ctx *RequestCtx) HTTPResponseBytes(body []byte, statusCode ...int) error

HTTPResponseBytes return response with body in html format

func (*RequestCtx) JSONResponse

func (ctx *RequestCtx) JSONResponse(body interface{}, statusCode ...int) error

JSONResponse return response with body in json format

func (*RequestCtx) RawResponse

func (ctx *RequestCtx) RawResponse(body string, statusCode ...int) error

RawResponse returns response without encoding the body.

func (*RequestCtx) RawResponseBytes

func (ctx *RequestCtx) RawResponseBytes(body []byte, statusCode ...int) error

RawResponseBytes returns response without encoding the body.

func (*RequestCtx) RedirectResponse

func (ctx *RequestCtx) RedirectResponse(url string, statusCode int) error

RedirectResponse redirect request to an especific url

func (*RequestCtx) RequestID

func (ctx *RequestCtx) RequestID() []byte

RequestID returns the "X-Request-ID" header value

func (*RequestCtx) TextResponse

func (ctx *RequestCtx) TextResponse(body string, statusCode ...int) error

TextResponse return response with body in text format

func (*RequestCtx) TextResponseBytes

func (ctx *RequestCtx) TextResponseBytes(body []byte, statusCode ...int) error

TextResponseBytes return response with body in text format

type Router added in v8.2.0

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

Router dispatchs requests to different views via configurable routes (paths)

It is prohibited copying Router values. Create new values instead.

func (*Router) ListPaths added in v8.2.0

func (r *Router) ListPaths() map[string][]string

ListPaths returns all registered routes grouped by method

func (*Router) NetHTTPPath added in v8.2.0

func (r *Router) NetHTTPPath(httpMethod, url string, handler http.Handler)

NetHTTPPath wraps net/http handler to atreugo view and registers it with the given path and method

While this function may be used for easy switching from net/http to fasthttp/atreugo, it has the following drawbacks comparing to using manually written fasthttp/atreugo, request handler:

  • A lot of useful functionality provided by fasthttp/atreugo is missing from net/http handler.
  • net/http -> fasthttp/atreugo handler conversion has some overhead, so the returned handler will be always slower than manually written fasthttp/atreugo handler.

So it is advisable using this function only for quick net/http -> fasthttp switching. Then manually convert net/http handlers to fasthttp handlers according to https://github.com/valyala/fasthttp#switching-from-nethttp-to-fasthttp .

func (*Router) NetHTTPPathWithFilters added in v8.2.0

func (r *Router) NetHTTPPathWithFilters(httpMethod, url string, handler http.Handler, filters Filters)

NetHTTPPathWithFilters wraps net/http handler to atreugo view and registers it to the given path and method, and with filters that will execute before and after

While this function may be used for easy switching from net/http to fasthttp/atreugo, it has the following drawbacks comparing to using manually written fasthttp/atreugo, request handler:

  • A lot of useful functionality provided by fasthttp/atreugo is missing from net/http handler.
  • net/http -> fasthttp/atreugo handler conversion has some overhead, so the returned handler will be always slower than manually written fasthttp/atreugo handler.

So it is advisable using this function only for quick net/http -> fasthttp switching. Then manually convert net/http handlers to fasthttp handlers according to https://github.com/valyala/fasthttp#switching-from-nethttp-to-fasthttp .

func (*Router) NewGroupPath added in v8.2.0

func (r *Router) NewGroupPath(path string) *Router

NewGroupPath returns a new router to group paths

func (*Router) Path added in v8.2.0

func (r *Router) Path(httpMethod, url string, viewFn View)

Path registers a new view with the given path and method.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*Router) PathWithFilters added in v8.2.0

func (r *Router) PathWithFilters(httpMethod, url string, viewFn View, filters Filters)

PathWithFilters registers a new view with the given path and method, and with filters that will execute before and after.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*Router) RequestHandlerPath added in v8.2.0

func (r *Router) RequestHandlerPath(httpMethod, url string, handler fasthttp.RequestHandler)

RequestHandlerPath wraps fasthttp request handler to atreugo view and registers it to the given path and method.

func (*Router) RequestHandlerPathWithFilters added in v8.2.0

func (r *Router) RequestHandlerPathWithFilters(httpMethod, url string, handler fasthttp.RequestHandler,
	filters Filters)

RequestHandlerPathWithFilters wraps fasthttp request handler to atreugo view and registers it to the given path and method, and with filters that will execute before and after.

func (*Router) ServeFile added in v8.2.0

func (r *Router) ServeFile(url, filePath string)

ServeFile returns HTTP response containing compressed file contents from the given path.

HTTP response may contain uncompressed file contents in the following cases:

  • Missing 'Accept-Encoding: gzip' request header.
  • No write access to directory containing the file.

Directory contents is returned if path points to directory.

func (*Router) Static added in v8.2.0

func (r *Router) Static(url, rootPath string)

Static serves static files from the given file system root.

Make sure your program has enough 'max open files' limit aka 'ulimit -n' if root folder contains many files.

func (*Router) StaticCustom added in v8.2.0

func (r *Router) StaticCustom(url string, fs *StaticFS)

StaticCustom serves static files from the given file system settings.

Make sure your program has enough 'max open files' limit aka 'ulimit -n' if root folder contains many files.

func (*Router) TimeoutPath added in v8.2.0

func (r *Router) TimeoutPath(httpMethod, url string, viewFn View, timeout time.Duration, msg string)

TimeoutPath registers a new view with the given path and method, which returns StatusRequestTimeout error with the given msg to the client if view didn't return during the given duration.

The returned handler may return StatusTooManyRequests error with the given msg to the client if there are more than Server.Concurrency concurrent handlers view are running at the moment.

func (*Router) TimeoutPathWithFilters added in v8.2.0

func (r *Router) TimeoutPathWithFilters(httpMethod, url string, viewFn View, filters Filters,
	timeout time.Duration, msg string)

TimeoutPathWithFilters registers a new view with the given path and method, and with filters that will execute before and after, which returns StatusRequestTimeout error with the given msg to the client if view/filters didn't return during the given duration.

The returned handler may return StatusTooManyRequests error with the given msg to the client if there are more than Server.Concurrency concurrent handlers view/filters are running at the moment.

func (*Router) TimeoutWithCodePath added in v8.2.0

func (r *Router) TimeoutWithCodePath(httpMethod, url string, viewFn View,
	timeout time.Duration, msg string, statusCode int)

TimeoutWithCodePath registers a new view with the given path and method, which returns an error with the given msg and status code to the client if view/filters didn't return during the given duration.

The returned handler may return StatusTooManyRequests error with the given msg to the client if there are more than Server.Concurrency concurrent handlers view/filters are running at the moment.

func (*Router) TimeoutWithCodePathWithFilters added in v8.2.0

func (r *Router) TimeoutWithCodePathWithFilters(httpMethod, url string, viewFn View, filters Filters,
	timeout time.Duration, msg string, statusCode int)

TimeoutWithCodePathWithFilters registers a new view with the given path and method, and with filters that will execute before and after, which returns an error with the given msg and status code to the client if view/filters didn't return during the given duration.

The returned handler may return StatusTooManyRequests error with the given msg to the client if there are more than Server.Concurrency concurrent handlers view/filters are running at the moment.

func (*Router) UseAfter added in v8.2.0

func (r *Router) UseAfter(fns ...Middleware)

UseAfter register middleware functions in the order you want to execute them after the view execution.

func (*Router) UseBefore added in v8.2.0

func (r *Router) UseBefore(fns ...Middleware)

UseBefore register middleware functions in the order you want to execute them before the view execution.

type StaticFS added in v8.2.0

type StaticFS struct {

	// Path to the root directory to serve files from.
	Root string

	// List of index file names to try opening during directory access.
	//
	// For example:
	//
	//     * index.html
	//     * index.htm
	//     * my-super-index.xml
	//
	// By default the list is empty.
	IndexNames []string

	// Index pages for directories without files matching IndexNames
	// are automatically generated if set.
	//
	// Directory index generation may be quite slow for directories
	// with many files (more than 1K), so it is discouraged enabling
	// index pages' generation for such directories.
	//
	// By default index pages aren't generated.
	GenerateIndexPages bool

	// Transparently compresses responses if set to true.
	//
	// The server tries minimizing CPU usage by caching compressed files.
	// It adds CompressedFileSuffix suffix to the original file name and
	// tries saving the resulting compressed file under the new file name.
	// So it is advisable to give the server write access to Root
	// and to all inner folders in order to minimize CPU usage when serving
	// compressed responses.
	//
	// Transparent compression is disabled by default.
	Compress bool

	// Enables byte range requests if set to true.
	//
	// Byte range requests are disabled by default.
	AcceptByteRange bool

	// Path rewriting function.
	//
	// By default request path is not modified.
	PathRewrite PathRewriteFunc

	// PathNotFound fires when file is not found in filesystem
	// this functions tries to replace "Cannot open requested path"
	// server response giving to the programmer the control of server flow.
	//
	// By default PathNotFound returns
	// "Cannot open requested path"
	PathNotFound View

	// Expiration duration for inactive file handlers.
	//
	// FSHandlerCacheDuration is used by default.
	CacheDuration time.Duration

	// Suffix to add to the name of cached compressed file.
	//
	// This value has sense only if Compress is set.
	//
	// FSCompressedFileSuffix is used by default.
	CompressedFileSuffix string
	// contains filtered or unexported fields
}

StaticFS represents settings for serving static files from the local filesystem.

It is prohibited copying StaticFS values. Create new values instead.

type View

type View func(*RequestCtx) error

View must process incoming requests.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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