atreugo

package module
v5.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2018 License: GPL-3.0 Imports: 17 Imported by: 0

README

Atreugo

Build Status Coverage Status Go Report Card GoDoc GitHub release

Micro-framework to make simple the use of routing and middlewares in fasthttp.

The project use dep manager dependencies.

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 😄

Example:

package main

import (
	"errors"

	"github.com/valyala/fasthttp"
	"github.com/savsgio/atreugo"
)

func main() {
	config := &atreugo.Config{
		Host: "0.0.0.0",
		Port: 8000,
	}
	server := atreugo.New(config)

	fnMiddlewareOne := func(ctx *atreugo.RequestCtx) (int, error) {
		return fasthttp.StatusOK, nil
	}

	fnMiddlewareTwo := func(ctx *atreugo.RequestCtx) (int, error) {
		// Disable this middleware if you don't want to see this error
		return fasthttp.StatusBadRequest, errors.New("Error example")
	}

	server.UseMiddleware(fnMiddlewareOne, fnMiddlewareTwo)

	server.Path("GET", "/", func(ctx *atreugo.RequestCtx) error {
		return ctx.HTTPResponse("<h1>Atreugo Micro-Framework</h1>")
	})

	server.Path("GET", "/jsonPage", func(ctx *atreugo.RequestCtx) error {
		return ctx.JSONResponse(atreugo.JSON{"Atreugo": true})
	})

	err := server.ListenAndServe()
	if err != nil {
		panic(err)
	}
}

Useful third-party libraries

Contributing

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

Documentation

Overview

Package atreugo is a micro-framework to make simple the use of routing and middlewares with all optimizations of fasthttp

This micro-framework is build on top valyala's fasthttp fork.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Atreugo

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

Atreugo struct for make up a server

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

func (s *Atreugo) Path(httpMethod string, url string, viewFn View)

Path add the views to serve

func (*Atreugo) Serve added in v5.4.0

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 added in v5.4.0

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

func (*Atreugo) Static

func (s *Atreugo) Static(rootStaticDirPath string)

Static add view for static files

func (*Atreugo) UseMiddleware

func (s *Atreugo) UseMiddleware(fns ...Middleware)

UseMiddleware register middleware functions that viewHandler will use

type Config

type Config struct {
	Host      string
	Port      int
	TLSEnable bool
	CertKey   string
	CertFile  string

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

	// Compress transparently the response body generated by handler if the request contains 'gzip' or 'deflate'
	// in 'Accept-Encoding' header.
	Compress 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

	// fasthttp server configuration
	Fasthttp *FasthttpConfig
}

Config config for Atreugo

type FasthttpConfig added in v5.4.0

type FasthttpConfig struct {
	// Server name for sending in response headers.
	//
	// Default server name is used if left blank.
	Name string

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

	// Maximum duration for reading the full request (including body).
	//
	// This also limits the maximum duration for idle keep-alive
	// connections.
	//
	// By default request read timeout is unlimited if Graceful Shutdown is set to false,
	// unless will use the default ReadTimeout
	ReadTimeout time.Duration

	// Maximum duration for writing the full response (including body).
	//
	// By default response write timeout is unlimited.
	WriteTimeout 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

	// Maximum keep-alive connection lifetime.
	//
	// The server closes keep-alive connection after its' lifetime
	// expiration.
	//
	// See also ReadTimeout for limiting the duration of idle keep-alive
	// connections.
	//
	// By default keep-alive connection lifetime is unlimited.
	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

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

FasthttpConfig fasthttp server configuration

It is a copy from https://godoc.org/github.com/valyala/fasthttp#Server without the fields: - Handler: It's created internaly by atreugo - TCPKeepalive: Not supported yet (You can implemented with a custom Listener and pass it directly to Serve) - TCPKeepalivePeriod: Not supported yet (You can implemented with a custom Listener and pass it directly to Serve) - Logger: It's created internaly by atreugo

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(ctx *RequestCtx) (int, error)

Middleware must process all incoming requests before defined views.

type RequestCtx

type RequestCtx struct {
	*fasthttp.RequestCtx
}

RequestCtx context wrapper for fasthttp.RequestCtx to adds extra funtionality

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

type View func(ctx *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