flow

package module
v1.4.4 Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2021 License: MIT Imports: 21 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

View Source
const (
	MIMEJSON              = "application/json"
	MIMEHTML              = "text/html"
	MIMEXML               = "application/xml"
	MIMEXML2              = "text/xml"
	MIMEPlain             = "text/plain"
	MIMEPOSTForm          = "application/x-www-form-urlencoded"
	MIMEMultipartPOSTForm = "multipart/form-data"
	MIMEYAML              = "application/x-yaml"
)

Content-Type MIME of the most common data formats.

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 ControllerRouter

type ControllerRouter interface {
	Routes(*Router)
}

ControllerRouter interface allows controllers to define their routing logic

type HandlerFunc

type HandlerFunc func(r *http.Request) Response

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

type Map added in v1.4.0

type Map map[string]interface{}

Map is shortcut for map[string]interface{}

type MiddlewareFunc added in v1.4.0

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

MiddlewareFunc defines middleware handler function

type MiddlewareHandlerFunc added in v1.4.0

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

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

MiddlewareStack holds middlewares applied to router

func (*MiddlewareStack) Append added in v1.4.0

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

Append new Middlewares to stack

func (*MiddlewareStack) Clear added in v1.4.0

func (mws *MiddlewareStack) Clear()

Clear current middleware stack

func (*MiddlewareStack) Clone added in v1.4.0

Clone current stack to new one abd apply new middlewares

type Module added in v1.4.0

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

Module struct

func Bootstrap added in v1.4.0

func Bootstrap(moduleFactory interface{}) (*Module, error)

Bootstrap creates Flow Module instance for given factory object

func NewModule added in v1.4.0

func NewModule(factory interface{}, container di.Container, parent *Module) (*Module, error)

NewModule creates new Module object

func (*Module) Path added in v1.4.0

func (m *Module) Path() string

Path returns module path

func (*Module) Router added in v1.4.0

func (m *Module) Router() (*Router, error)

Router gets router, if router is not initialized router is initialized

func (*Module) Serve added in v1.4.0

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

type ModuleController interface {
	Controllers() []interface{}
}

ModuleController interface allows module to define Controllers

type ModuleExporter added in v1.4.0

type ModuleExporter interface {
	Exports() []interface{}
}

ModuleExporter interface is used for exporting functionalities to modules that import the module

type ModuleImporter added in v1.4.0

type ModuleImporter interface {
	Imports() []interface{}
}

ModuleImporter interface is used to for providing list of imported modules that export providers that arerequired in this module

type ModuleIniter added in v1.4.0

type ModuleIniter interface {
	Init() error
}

ModuleIniter is interface used for Module Initialization

type ModuleMiddleware added in v1.4.0

type ModuleMiddleware interface {
	Middlewares() []MiddlewareHandlerFunc
}

ModuleMiddleware interface allows module to define their routing middlewares

type ModuleOptioner added in v1.4.0

type ModuleOptioner interface {
	Options() Options
}

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

type ModulePather added in v1.4.0

type ModulePather interface {
	Path() string
}

ModulePather is interface used to define http path for Module

type ModuleProvider added in v1.4.0

type ModuleProvider interface {
	Providers() []interface{}
}

ModuleProvider is interface used for injecting dependecies that can be used in the module

type ModuleRouter added in v1.4.0

type ModuleRouter interface {
	Router() *Router
}

ModuleRouter interface alows module to define custom Routing

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

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 Response

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

Response defines interface for HTTP action responses

func ResponseData added in v1.4.0

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

ResponseData creates []byte render Response

func ResponseDownload added in v1.4.0

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

func ResponseError(code int, err error) Response

ResponseError creates new Error response for given http code and error

func ResponseFile added in v1.4.0

func ResponseFile(filepath string) Response

ResponseFile serves content from given file

func ResponseHeader added in v1.4.4

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

func ResponseJSON added in v1.4.0

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

ResponseJSON creates JSON rendered Response

func ResponseReader added in v1.4.0

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

func ResponseRedirect(code int, url string) Response

ResponseRedirect creates Redirect ewsponse for given http code and destination URL

func ResponseText added in v1.4.0

func ResponseText(code int, text string) Response

ResponseText creates Text rendered Response

func ResponseXML added in v1.4.0

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
}

Route structure

func (*Route) HandleRequest added in v1.4.0

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

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

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

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

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