flamego

package module
Version: v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2021 License: MIT Imports: 26 Imported by: 15

README

Flamego Flamego

GitHub Workflow Status Codecov GoDoc Sourcegraph

Flamego is a fantastic modular Go web framework boiled with dependency injection.

It is the successor of the Macaron, and equips the most powerful routing syntax among all web frameworks within the Go ecosystem.

Installation

The minimum requirement of Go is 1.16.

go get github.com/flamego/flamego

Getting started

package main

import "github.com/flamego/flamego"

func main() {
	f := flamego.Classic()
	f.Get("/", func() string {
		return "Hello, Flamego!"
	})
	f.Run()
}

Features

Middleware

  • Logger - Log requests and response status code
  • Recovery - Automatic recovery from panics
  • Static - Serve static files
  • Renderer - Render content
  • template - Go template rendering
  • session - User session management
  • recaptcha - Google reCAPTCHA verification
  • csrf - Generate and validate CSRF tokens
  • cors - Cross-Origin Resource Sharing
  • binding - Request data binding and validation
  • gzip - Gzip compression to responses
  • cache - Cache management
  • brotli - Brotli compression to responses
  • auth - Basic and bearer authentication
  • i18n - Internationalization and localization
  • captcha - Captcha service

Getting help

Users and projects

  • Cardinal: Attack-defence CTF platform.
  • mebeats: Realtime heartbeat monitor service based on Mi band.
  • Just send a PR to add yours!

License

This project is under the MIT License. See the LICENSE file for the full license text.

Documentation

Overview

Package flamego is a fantastic modular Go web framework boiled with black magic.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetEnv

func SetEnv(e EnvType)

SetEnv sets the current runtime environment. Valid values are EnvTypeDev, EnvTypeProd and EnvTypeTest, all else ignored.

Types

type BeforeFunc

type BeforeFunc func(ResponseWriter)

BeforeFunc is a function that is called before the ResponseWriter is written.

type BeforeHandler

type BeforeHandler func(rw http.ResponseWriter, req *http.Request) bool

BeforeHandler is a handler executes at beginning of every request. Flame instance stops further process when it returns true.

type ComboRoute

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

ComboRoute is a wrapper of the router for adding handlers of different HTTP methods to the same route.

func (*ComboRoute) Connect

func (r *ComboRoute) Connect(handlers ...Handler) *ComboRoute

Connect adds handlers of the CONNECT method to the route.

func (*ComboRoute) Delete

func (r *ComboRoute) Delete(handlers ...Handler) *ComboRoute

Delete adds handlers of the DELETE method to the route.

func (*ComboRoute) Get

func (r *ComboRoute) Get(handlers ...Handler) *ComboRoute

Get adds handlers of the GET method to the route.

func (*ComboRoute) Head

func (r *ComboRoute) Head(handlers ...Handler) *ComboRoute

Head adds handlers of the HEAD method to the route.

func (*ComboRoute) Name

func (r *ComboRoute) Name(name string)

Name sets the name for the route.

func (*ComboRoute) Options

func (r *ComboRoute) Options(handlers ...Handler) *ComboRoute

Options adds handlers of the OPTIONS method to the route.

func (*ComboRoute) Patch

func (r *ComboRoute) Patch(handlers ...Handler) *ComboRoute

Patch adds handlers of the PATCH method to the route.

func (*ComboRoute) Post

func (r *ComboRoute) Post(handlers ...Handler) *ComboRoute

Post adds handlers of the POST method to the route.

func (*ComboRoute) Put

func (r *ComboRoute) Put(handlers ...Handler) *ComboRoute

Put adds handlers of the PUT method to the route.

func (*ComboRoute) Trace

func (r *ComboRoute) Trace(handlers ...Handler) *ComboRoute

Trace adds handlers of the TRACE method to the route.

type Context

type Context interface {
	inject.Injector
	// ResponseWriter returns the ResponseWriter in current context.
	ResponseWriter() ResponseWriter
	// Request returns the Request in current context.
	Request() *Request

	// URLPath builds the "path" portion of URL with given pairs of values. To
	// include the optional segment, pass `"withOptional", "true"`.
	//
	// This is a transparent wrapper of Router.URLPath.
	URLPath(name string, pairs ...string) string

	// Next runs the next handler in the context chain.
	Next()
	// RemoteAddr extracts and returns the remote IP address from following attempts
	// in sequence:
	//  - "X-Real-IP" request header
	//  - "X-Forwarded-For" request header
	//  - http.Request.RemoteAddr field
	RemoteAddr() string
	// Redirect sends a redirection to the response to the given location. If the
	// `status` is not given, the http.StatusFound is used.
	Redirect(location string, status ...int)

	// Params returns all bind parameters.
	Params() Params
	// Param returns value of the given bind parameter.
	Param(name string) string
	// ParamInt returns value of the given bind parameter parsed as int.
	ParamInt(name string) int
	// ParamInt64 returns value of the given bind parameter parsed as int64.
	ParamInt64(name string) int64

	// Query returns value of the given URL parameter.
	Query(name string) string
	// QueryTrim trims spaces and returns value of the given URL parameter.
	QueryTrim(name string) string
	// QueryStrings returns a list of strings of the given URL parameter.
	QueryStrings(name string) []string
	// QueryUnescape returns unescaped query result of the given URL parameter.
	QueryUnescape(name string) string
	// QueryBool returns value of the given URL parameter parsed as bool.
	QueryBool(name string) bool
	// QueryInt returns value of the given URL parameter parsed as int.
	QueryInt(name string) int
	// QueryInt64 returns value of the given URL parameter parsed as int64.
	QueryInt64(name string) int64
	// QueryFloat64 returns value of the given URL parameter parsed as float64.
	QueryFloat64(name string) float64

	// SetCookie escapes the cookie value and sets it to the current response.
	SetCookie(cookie http.Cookie)
	// Cookie returns the named cookie in the request or empty if not found. If
	// multiple cookies match the given name, only one cookie will be returned. The
	// returned value is unescaped using `url.QueryUnescape`, original value is
	// returned instead if unable to unescape.
	Cookie(name string) string
	// contains filtered or unexported methods
}

Context is the runtime context of the coming request, and provide handy methods to enhance developer experience.

type ContextInvoker

type ContextInvoker func(ctx Context)

ContextInvoker is an inject.FastInvoker implementation of `func(Context)`.

func (ContextInvoker) Invoke

func (invoke ContextInvoker) Invoke(args []interface{}) ([]reflect.Value, error)

type EnvType

type EnvType string

EnvType defines the runtime environment.

const (
	EnvTypeDev  EnvType = "development"
	EnvTypeProd EnvType = "production"
	EnvTypeTest EnvType = "test"
)

func Env

func Env() EnvType

Env returns the current runtime environment. It can be altered by SetEnv or the environment variable "FLAMEGO_ENV".

type Flame

type Flame struct {
	inject.Injector
	Router
	// contains filtered or unexported fields
}

Flame is the top-level web application instance, which manages global states of injected services and middleware.

func Classic

func Classic() *Flame

Classic creates and returns a classic Flame instance with default middleware: `flamego.Logger`, `flamego.Recovery` and `flamego.Static`.

func New

func New() *Flame

New creates and returns a bare bones Flame instance with default logger writing to os.Stdout. Use this function if you want to have full control over middleware that are used.

func NewWithLogger

func NewWithLogger(w io.Writer) *Flame

NewWithLogger creates and returns a bare bones Flame instance. Use this function if you want to have full control over log destination and middleware that are used.

func (*Flame) Action

func (f *Flame) Action(h Handler)

Action sets the final handler that will be called after all handlers have been invoked.

func (*Flame) Before

func (f *Flame) Before(h BeforeHandler)

Before allows for a handler to be called before matching any route. Multiple calls to this method will queue up handlers, and handlers will be called in the FIFO manner.

func (*Flame) Handlers

func (f *Flame) Handlers(handlers ...Handler)

Handlers sets the entire middleware stack with the given Handlers. This will clear any current middleware handlers, and panics if any of the handlers is not a callable function.

func (*Flame) Run

func (f *Flame) Run(args ...interface{})

Run starts the HTTP server on "0.0.0.0:2830". The listen address can be altered by the environment variable "FLAMEGO_ADDR". The instance can be stopped by calling `Flame.Stop`.

func (*Flame) ServeHTTP

func (f *Flame) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Flame) Stop

func (f *Flame) Stop()

Stop stops the server started by the Flame instance.

func (*Flame) Use

func (f *Flame) Use(handlers ...Handler)

Use adds handlers of middleware to the Flame instance, and panics if any of the handler is not a callable func. Middleware handlers are invoked in the same order as they are added.

type Handler

type Handler interface{}

Handler is any callable function. Flamego attempts to inject services into the Handler's argument list and panics if any argument could not be fulfilled via dependency injection.

func Logger

func Logger(opts ...LoggerOptions) Handler

Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.

func Recovery

func Recovery() Handler

Recovery returns a middleware handler that recovers from any panics and writes a 500 status code to the response if there was one. While in development mode (EnvTypeDev), Recovery will also output the panic as HTML.

func Renderer

func Renderer(opts ...RenderOptions) Handler

Renderer returns a middleware handler that injects flamego.Render into the request context, which is used for rendering content to the ResponseWriter.

func Static

func Static(opts ...StaticOptions) Handler

Static returns a middleware handler that serves static files in the given directory.

type LoggerInvoker

type LoggerInvoker func(ctx Context, log *log.Logger)

LoggerInvoker is an inject.FastInvoker implementation of `func(ctx Context, log *log.Logger)`.

func (LoggerInvoker) Invoke

func (invoke LoggerInvoker) Invoke(params []interface{}) ([]reflect.Value, error)

type LoggerOptions

type LoggerOptions struct {
	// LogTimeFormat specifies the time format for the logger. The default format is
	// "2006-01-02 15:04:05".
	LogTimeFormat string
}

LoggerOptions contains options for the flamego.Logger middleware.

type Params

type Params map[string]string

Params is a set of bind parameters with their values that are extracted from the request path.

type Render

type Render interface {
	// JSON encodes given value in JSON format with given status code to the
	// ResponseWriter.
	JSON(status int, v interface{})
	// XML encodes given value in XML format with given status code to the
	// ResponseWriter.
	XML(status int, v interface{})
	// Binary writes binary data with given status code to the ResponseWriter.
	Binary(status int, v []byte)
	// PlainText writes string with given status code to the ResponseWriter.
	PlainText(status int, s string)
}

Render is a thin wrapper to render content to the ResponseWriter.

type RenderOptions

type RenderOptions struct {
	// Charset specifies the value of the "charset" to be responded with the
	// "Content-Type" header. Default is "utf-8".
	Charset string
	// JSONIndent specifies the indent value when encoding content in JSON format.
	// Default is no indentation.
	JSONIndent string
	// XMLIndent specifies the indent value when encoding content in XML format.
	// Default is no indentation.
	XMLIndent string
}

RenderOptions contains options for the flamego.Renderer middleware.

type Request

type Request struct {
	*http.Request
}

Request is a wrapper of http.Request with handy methods.

func (*Request) Body

func (r *Request) Body() *RequestBody

Body returns a RequestBody for the request.

type RequestBody

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

RequestBody is a wrapper of http.Request.Body with handy methods.

func (*RequestBody) Bytes

func (r *RequestBody) Bytes() ([]byte, error)

Bytes reads and returns the content of request body in bytes.

func (*RequestBody) ReadCloser

func (r *RequestBody) ReadCloser() io.ReadCloser

ReadCloser returns a ReadCloser of request body.

func (*RequestBody) String

func (r *RequestBody) String() (string, error)

String reads and returns content of request body in string.

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	http.Pusher
	// Status returns the status code of the response or 0 if the response has not
	// been written.
	Status() int
	// Written returns whether the ResponseWriter has been written.
	Written() bool
	// Size returns the written size of the response body.
	Size() int
	// Before allows for a function to be called before the ResponseWriter has been
	// written to. This is useful for setting headers or any other operations that
	// must happen before a response has been written. Multiple calls to this method
	// will stack up functions, and functions will be called in the FILO manner.
	Before(BeforeFunc)
}

ResponseWriter is a wrapper of http.ResponseWriter that provides extra information about the response. It is recommended that middleware handlers use this construct to wrap a ResponseWriter if the functionality calls for it.

func NewResponseWriter

func NewResponseWriter(method string, w http.ResponseWriter) ResponseWriter

NewResponseWriter returns a wrapper of http.ResponseWriter.

type ReturnHandler

type ReturnHandler func(Context, []reflect.Value)

ReturnHandler is a service that is called when a route handler returns something. The ReturnHandler is responsible for writing to the ResponseWriter based on the values that are passed into this function.

type Route

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

Route is a wrapper of the route leaf and its router.

func (*Route) Name

func (r *Route) Name(name string)

Name sets the name for the route.

type Router

type Router interface {
	// AutoHead sets a boolean value which determines whether to add HEAD method
	// automatically when GET method is added. Only routes that are added after call
	// of this method will be affected, existing routes remain unchanged.
	AutoHead(v bool)
	// HandlerWrapper sets handlerWrapper for the router. It is used to wrap Handler
	// and inject logic, and is especially useful for wrapping the Handler to
	// inject.FastInvoker.
	HandlerWrapper(f func(Handler) Handler)
	// Route adds the new route path and its handlers to the router tree.
	Route(method, routePath string, handlers []Handler) *Route
	// Combo returns a ComboRoute for adding handlers of different HTTP methods to
	// the same route.
	Combo(routePath string, handlers ...Handler) *ComboRoute
	// Group pushes a new group with the given route path and its handlers, it then
	// pops the group when leaves the scope of `fn`.
	Group(routePath string, fn func(), handlers ...Handler)
	// Get is a shortcut for `r.Route(http.MethodGet, routePath, handlers)`.
	Get(routePath string, handlers ...Handler) *Route
	// Patch is a shortcut for `r.Route(http.MethodPatch, routePath, handlers)`.
	Patch(routePath string, handlers ...Handler) *Route
	// Post is a shortcut for `r.Route(http.MethodPost, routePath, handlers)`.
	Post(routePath string, handlers ...Handler) *Route
	// Put is a shortcut for `r.Route(http.MethodPut, routePath, handlers)`.
	Put(routePath string, handlers ...Handler) *Route
	// Delete is a shortcut for `r.Route(http.MethodDelete, routePath, handlers)`.
	Delete(routePath string, handlers ...Handler) *Route
	// Options is a shortcut for `r.Route(http.MethodOptions, routePath, handlers)`.
	Options(routePath string, handlers ...Handler) *Route
	// Head is a shortcut for `r.Route(http.MethodHead, routePath, handlers)`.
	Head(routePath string, handlers ...Handler) *Route
	// Connect is a shortcut for `r.Route(http.MethodConnect, routePath, handlers)`.
	Connect(routePath string, handlers ...Handler) *Route
	// Trace is a shortcut for `r.Route(http.MethodTrace, routePath, handlers)`.
	Trace(routePath string, handlers ...Handler) *Route
	// Any is a shortcut for `r.Route("*", routePath, handlers)`.
	Any(routePath string, handlers ...Handler) *Route
	// Routes is a shortcut of adding same handlers for different HTTP methods.
	//
	// Example:
	//	f.Routes("/", "GET,POST", handlers)
	Routes(routePath, methods string, handlers ...Handler) *Route
	// NotFound configures a http.HandlerFunc to be called when no matching route is
	// found. When it is not set, http.NotFound is used. Be sure to set
	// http.StatusNotFound as the response status code in your last handler.
	NotFound(handlers ...Handler)
	// URLPath builds the "path" portion of URL with given pairs of values. To
	// include the optional segment, pass `"withOptional", "true"`.
	URLPath(name string, pairs ...string) string
	// ServeHTTP implements the method of http.Handler.
	ServeHTTP(w http.ResponseWriter, req *http.Request)
}

Router is the router for adding routes and their handlers.

type StaticOptions

type StaticOptions struct {
	// Directory is the local directory to be used to serve static file. This value
	// is ignored when FileSystem is set. Default is "public".
	Directory string
	// FileSystem is the interface for supporting any implementation of the
	// http.FileSystem.
	FileSystem http.FileSystem
	// Prefix is the optional prefix used to serve the static directory content.
	Prefix string
	// Index specifies which file to attempt to serve as the directory index.
	// Default is "index.html".
	Index string
	// Expires is used to set the "Expires" response header for every static file
	// that is served. Default is not set.
	Expires func() string
	// SetETag indicates whether to compute and set "ETag" response header for every
	// static file that is served. File name, size and modification time are used to
	// compute the value.
	SetETag bool
	// EnableLogging indicates whether to print "[Static]" log messages whenever a
	// static file is served.
	EnableLogging bool
}

StaticOptions contains options for the flamego.Static middleware.

Directories

Path Synopsis
Package inject provides utilities for mapping and injecting dependencies in various ways.
Package inject provides utilities for mapping and injecting dependencies in various ways.
internal

Jump to

Keyboard shortcuts

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