flow

package module
v2.0.8 Latest Latest
Warning

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

Go to latest
Published: May 4, 2021 License: MIT Imports: 17 Imported by: 0

README

A Progressive Go for building efficient and scalable server-side applications.

Build Status codecov GoDoc GoReport GitHub contributors

Description

Flow is a web framework for building efficient, scalable Go (Golang) applications.

Thanks to httprouter library, flow provides lightweight high performance HTTP request router. If you need performance and good productivity, flow is right tool for you :)

Philosophy

In recent years Go is gaining in populariti on the web for building REST APIs and microservices. there are a lot of amazing libraries, helpers and tools available for Go, none of them effectively solve the main problem - the architecture.

Flow aims to provide an application architecture out of the box which allows for effortless creation of highly testable, scalable, loosely coupled and easily maintainable applications.

Getting started

Github pages link page comming soon

Issues

Please make sure to read the Issue Reporting Checklist before opening an issue. Issues not conforming to the guideliness may be closed immediately.

Support

Flow is an MIT-licensed open source project. It can grow thanks to the Ministry of Programming and amazing team.

License

Flow is MIT licensed.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ParamsKey = paramsKey{}

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

Functions

func CleanPath

func CleanPath(p string) string

CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.

The following rules are applied iteratively until no further processing can be done:

  1. Replace multiple slashes with a single slash.
  2. Eliminate each . path name element (the current directory).
  3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.

If the result of this process is an empty string, "/" is returned

Types

type ActionHandler

type ActionHandler interface {
	Method() string
	Path() string
	Middlewares() []MiddlewareHandlerFunc
	Handle(r *http.Request) Response
}

ActionHandler interface is used to define http action handlers defined by module router

type HandlerFunc

type HandlerFunc func(r *http.Request) Response

HandlerFunc is a function that is registered to a route to handle http requests

type Injector

type Injector interface {
	Provide(constructor interface{}) (interface{}, error)
}

Injector defines Dependency Injector interface

type Map

type Map map[string]interface{}

Map is shortcut for map[string]interface{}

type MiddlewareFunc

type MiddlewareFunc func(w http.ResponseWriter, r *http.Request) Response

MiddlewareFunc defines middleware handler function

type MiddlewareHandlerFunc

type MiddlewareHandlerFunc func(MiddlewareFunc) MiddlewareFunc

MiddlewareHandlerFunc defines middleware interface

func DoSomething(next MiddlewareFunc) MiddlewareFunc {
	return func(w http.ResponseWriter, r *http.Request) Response {
		// do something before calling the next handler
		resp := next(w, r)
		// do something after call the handler
		return resp
	}
}

type MiddlewareStack

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

MiddlewareStack holds middlewares applied to router

func (*MiddlewareStack) Append

func (mws *MiddlewareStack) Append(mw ...MiddlewareHandlerFunc)

Append new Middlewares to stack

func (*MiddlewareStack) Clear

func (mws *MiddlewareStack) Clear()

Clear current middleware stack

func (*MiddlewareStack) Clone

Clone current stack to new one abd apply new middlewares

type Module

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

Module struct

func Bootstrap

func Bootstrap(moduleFactory ModuleFactory) (*Module, error)

Bootstrap creates Flow Module instance for given factory object

func NewModule

func NewModule(factory ModuleFactory, container di.Container, parent *Module) (*Module, error)

NewModule creates new Module object

func (*Module) IsRoot

func (m *Module) IsRoot() bool

func (*Module) Serve

func (m *Module) Serve() error

Serve the application at the specified address/port and listen for OS interrupt and kill signals and will attempt to stop the application gracefully.

type ModuleFactory

type ModuleFactory interface {

	// ProvideImports returns list of instance providers for module dependecies
	// This method is used to register all module dependecies
	// eg. logging, db connection,....
	// all dependecies that are provided in this method
	// will be available to all modules imported by the factory
	ProvideImports() []Provider

	// ProvideExports returns list of instance providers for
	// functionalities that module will export.
	// Exported functionalities will be available to other modules that
	// import module created by the Factory
	ProvideExports() []Provider

	// ProvideModules returns list of instance providers
	// for modules that current module depends on
	ProvideModules() []Provider

	// ProvideRouters returns list of instance providers for module routers.
	// Module routers are used for http routing
	ProvideRouters() []Provider
}

ModuleFactory interface for creating flow.Module

type ModuleOptioner

type ModuleOptioner interface {
	Options() Options
}

ModuleOptioner interface is used for providing Application Options This interface is used only for root module or AppModule

type ModuleStarter

type ModuleStarter interface {
	Start() error
}

ModuleStarter interface used when http application is served Start method is invoked if module implements the interface

type ModuleStopper

type ModuleStopper interface {
	Stop()
}

ModuleStopper interface used when http application is stopped Stop method is invoked during shutdown process if module implements the interface

type Options

type Options struct {
	RouterOptions

	Env              string
	Name             string
	Addr             string
	Version          string
	ModuleSuffix     string
	ControllerSuffix string
	ControllerIndex  string
	// contains filtered or unexported fields
}

Options holds application configuration Options

func NewOptions

func NewOptions() Options

NewOptions creates New application Options instance

type Param

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

type Params

type Params []Param

Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func ParamsFromContext

func ParamsFromContext(ctx context.Context) Params

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

func (Params) ByName

func (ps Params) ByName(name string) string

ByName 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 (Params) Get

func (ps Params) Get(name string) (string, bool)

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

type Provider

type Provider interface {
	Provide(injector Injector) (interface{}, error)
}

func NewProvider

func NewProvider(constructor interface{}) Provider

type Response

type Response interface {
	Status() int
	Handle(w http.ResponseWriter, r *http.Request) error
}

Response defines interface for HTTP action responses

func ResponseData

func ResponseData(code int, data []byte, contentType []string) Response

ResponseData creates []byte render Response

func ResponseDownload

func ResponseDownload(name string, reader io.Reader) Response

ResponseDownload creates file attachment ActionResult with following headers:

Content-Type
Content-Length
Content-Disposition

Content-Type is set using mime#TypeByExtension with the filename's extension. Content-Type will default to application/octet-stream if using a filename with an unknown extension.

func ResponseError

func ResponseError(code int, err error) Response

ResponseError creates new Error response for given http code and error

func ResponseFile

func ResponseFile(filepath string) Response

ResponseFile serves content from given file

func ResponseHeader

func ResponseHeader(code int, headers map[string]string) Response

func ResponseJSON

func ResponseJSON(code int, data interface{}) Response

ResponseJSON creates JSON rendered Response

func ResponseReader

func ResponseReader(code int, reader io.Reader, contentType []string) Response

ResponseReader creates io.Reader render Response for given http code, reader and content type

func ResponseRedirect

func ResponseRedirect(code int, url string) Response

ResponseRedirect creates Redirect ewsponse for given http code and destination URL

func ResponseText

func ResponseText(code int, text string) Response

ResponseText creates Text rendered Response

func ResponseXML

func ResponseXML(code int, data interface{}) Response

ResponseXML creates XML rendered Response

type Route

type Route struct {
	Method  string
	Path    string
	Mws     *MiddlewareStack
	Handler HandlerFunc
	// contains filtered or unexported fields
}

Route structure

func (*Route) HandleRequest

func (rt *Route) HandleRequest(w http.ResponseWriter, r *http.Request) Response

HandleRequest handles http request. It executes all route middlewares and action handler

type Router

type Router struct {

	// 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 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 NotFound
	// handler.
	HandleMethodNotAllowed bool

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

	// Body404 string to be displayed when route is not found
	Body404 string

	// Body405 string to be displayed when route is not allowed
	Body405 string
	// contains filtered or unexported fields
}

Router is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes

func NewRouter

func NewRouter() *Router

NewRouter creates new Router instance with default options

func NewRouterWithOptions

func NewRouterWithOptions(opts RouterOptions) *Router

NewRouterWithOptions creates new Router instance for given options

func (*Router) Attach

func (r *Router) Attach(prefix string, router *Router)

Attach another router to current one

func (*Router) AttachRoutes

func (r *Router) AttachRoutes(prefix string, routes Routes)

AttachRoutes to current routes

func (*Router) DELETE

func (r *Router) DELETE(path string, handler HandlerFunc, middlewares ...MiddlewareHandlerFunc)

DELETE is a shortcut for router.Handle(http.MethodDelete, path, handler)

func (*Router) GET

func (r *Router) GET(path string, handler HandlerFunc, middlewares ...MiddlewareHandlerFunc)

GET is a shortcut for router.Handle(http.MethodGet, path, handler)

func (*Router) Group

func (r *Router) Group(path string, middlewares ...MiddlewareHandlerFunc) *Router

Group creates a new router group.

You should add all the routes that have common middlewares or the same path prefix. For example, all the routes that use a common middleware for authorization could be grouped.

func (*Router) HEAD

func (r *Router) HEAD(path string, handler HandlerFunc, middlewares ...MiddlewareHandlerFunc)

HEAD is a shortcut for router.Handle(http.MethodHead, path, handler)

func (*Router) Handle

func (r *Router) Handle(method, path string, handler HandlerFunc, middlewares ...MiddlewareHandlerFunc)

Handle registers a new request handle with the given path and method.

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

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

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

Lookup allows the manual lookup of a method + path combo. This is e.g. useful to build a framework around this router. If the path was found, it returns the handle function and the path parameter values. Otherwise the third return value indicates whether a redirection to the same path with an extra / without the trailing slash should be performed.

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handler HandlerFunc, middlewares ...MiddlewareHandlerFunc)

OPTIONS is a shortcut for router.Handle(http.MethodOptions, path, handler)

func (*Router) PATCH

func (r *Router) PATCH(path string, handler HandlerFunc, middlewares ...MiddlewareHandlerFunc)

PATCH is a shortcut for router.Handle(http.MethodPatch, path, handler)

func (*Router) POST

func (r *Router) POST(path string, handler HandlerFunc, middlewares ...MiddlewareHandlerFunc)

POST is a shortcut for router.Handle(http.MethodPost, path, handler)

func (*Router) PUT

func (r *Router) PUT(path string, handler HandlerFunc, middlewares ...MiddlewareHandlerFunc)

PUT is a shortcut for router.Handle(http.MethodPut, path, handler)

func (*Router) Routes

func (r *Router) Routes() (routes Routes)

Routes returns a slice of registered routes

func (*Router) ServeHTTP

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

func (*Router) Use

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

Use appends one or more middlewares to middleware stack.

type RouterFactory

type RouterFactory interface {
	Path() string
	Middlewares() []MiddlewareHandlerFunc
	ProvideHandlers() []Provider
	RegisterSubRouters() bool
}

RouterFactory interface responsible for creating module routers

type RouterOptions

type RouterOptions struct {
	RedirectTrailingSlash  bool
	RedirectFixedPath      bool
	HandleMethodNotAllowed bool
	SaveMatchedRoutePath   bool
	HandleOptions          bool
	Body404                string
	Body405                string
}

RouterOptions holds router configuration Options

type Routes

type Routes []Route

Routes is Route collection

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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