gramework

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2017 License: Apache-2.0 Imports: 29 Imported by: 0

README

gramework codecov Build Status

The Good Framework

GoDoc

Gophers Slack #gramework channel

Discord Server

What is it?

Fast, highly effective and go-way web framework. You get the simple yet powerful API, we handle optimizations internally. We glad to see your feature requests and PRs, that are implemented as fast as possible while keeping framework high quality. SPA-first, so template engine support is WIP.

Project history and "Why?"

Basically, before I've started the project, I need a simple, powerful framework with fair license policy. First I consulted with lawyers, which license to choose, based on the list of packages that I need to use. Next, we discussed what to do in order to do everything as correctly as possible.

In our days, net/http-based projects are slow and cost-ineffective, so I just write the basic version.

But.

Those support HTTP/2, but theoretically we can make it work even with fasthttp.

Those also support websockets, but this is already was done.

But. Again.

All our company's solutions are based on fasthttp, so we can use our already stable, optimized solutions.

We can provide stable, faster and more effective functionality with really simple API.

We can support net/http handlers with compatibility layer.

We can support multiple handler signature, allow runtime route registration etc.

And even more We can.


So - why you may want to use it?

  • Gramework is battle-tested
  • Gramework is one of the rare frameworks that can help you serve up to 800k rps even on a 4Gb RAM/i5@2.9GHz/2x1Gbit server
  • Gramework make your projects' infrastructure costs more effective by using as less memory as possible
  • Gramework helps you serve requests faster, and so it helps you increase conversions (source 1, source 2)
  • You can build software faster with simple API
  • You can achieve agile support and get answers to your questions
  • You can just ask a feature and most likely it will be implemented and built in
  • You can contact me and donate for high priority feature
  • You can be sure that all license questions are OK with gramework
  • You can buy a corporate-grade support
API status

Stable, but not frozen: we adding functions, packages or optional arguments, so you can use new features, but we never break your projects.

Go >= 1.8 is supported.

Please, fire an issue or pull request if you want any feature, you find a bug or know how to optimize gramework even more.

Using Gramework with dep is highly recommended.

TOC

Benchmarks

benchmark

3rd-party license info

  • Gramework is now powered by fasthttp and custom fasthttprouter, that is embedded now. You can find licenses in /3rd-Party Licenses/fasthttp and /3rd-Party Licenses/fasthttprouter.
  • The 3rd autoTLS implementation, placed in nettls_*.go, is an integrated version of caddytls, because using it by simple import isn't an option: gramework based on fasthttp, that is incompatible with net/http. In the commit I based on, caddy is Apache-2.0 licensed. It's license placed in /3rd-Party Licenses/caddy. @mholt allow us to copy the code in this repo.

Basic usage

Hello world

The example below will serve "hello, grameworld" and register flag "bind", that allows you to choose another ip/port that gramework should listen:

package main

import (
	"github.com/gramework/gramework"
)

func main() {
	app := gramework.New()

        app.GET("/", "hello, grameworld")

        app.ListenAndServe()
}
Serving a dir

The example below will serve static files from ./files and register flag "bind", that allows you to choose another ip/port that gramework should listen:

package main

import (
	"github.com/gramework/gramework"
)

func main() {
	app := gramework.New()

	app.GET("/*any", app.ServeDir("./files"))

	app.ListenAndServe()
}
Serving prepared bytes

The example below will serve bytes and register flag "bind", that allows you to choose another ip/port that gramework should listen:

package main

import (
	"github.com/gramework/gramework"
)

func main() {
	app := gramework.New()

	app.GET("/*any", []byte("some data"))

	app.ListenAndServe()
}
Using dynamic handlers, part 1

The example below will serve JSON and register flag "bind", that allows you to choose another ip/port that gramework should listen:

package main

import (
	"github.com/gramework/gramework"
)

func main() {
	app := gramework.New()

	app.GET("/someJSON", func(ctx *gramework.Context) {
		m := map[string]interface{}{
			"name": "Grame",
			"age": 20,
		}

		if err := ctx.JSON(m); err != nil {
			ctx.Err500()
		}
	})

	app.ListenAndServe()
}
Using dynamic handlers, part 2

The example below will serve JSON with CORS enabled for all routes and register flag "bind", that allows you to choose another ip/port that gramework should listen:

package main

import (
	"github.com/gramework/gramework"
)

func main() {
	app := gramework.New()

	app.Use(app.CORSMiddleware())

	app.GET("/someJSON", func(ctx *gramework.Context) {
		m := map[string]interface{}{
			"name": "Grame",
			"age": 20,
		}

		if err := ctx.JSON(m); err != nil {
			ctx.Err500()
		}
	})

	app.ListenAndServe()
}
Using dynamic handlers, part 3

The example below will serve JSON with CORS enabled in the handler and register flag "bind", that allows you to choose another ip/port that gramework should listen:

package main

import (
	"github.com/gramework/gramework"
)

func main() {
	app := gramework.New()

	app.GET("/someJSON", func(ctx *gramework.Context) {
		ctx.CORS()

		m := map[string]interface{}{
			"name": "Grame",
			"age": 20,
		}

		if err := ctx.JSON(m); err != nil {
			ctx.Err500()
		}
	})

	app.ListenAndServe()
}
Using dynamic handlers, part 4

The example below will serve a string and register flag "bind", that allows you to choose another ip/port that gramework should listen:

package main

import (
	"github.com/gramework/gramework"
)

func main() {
	app := gramework.New()

	app.GET("/someJSON", func(ctx *fasthttp.RequestCtx) {
		ctx.WriteString("another data")
	})

	app.ListenAndServe()
}
Using dynamic handlers, part 5

The example below shows how you can get fasthttp.RequestCtx from gramework.Context and after that it do the same that in part 3:

package main

import (
	"github.com/gramework/gramework"
)

func main() {
	app := gramework.New()

	app.GET("/someJSON", func(ctx *gramework.Context) {
		// same as ctx.WriteString("another data")
		ctx.RequestCtx.WriteString("another data")
	})

	app.ListenAndServe()
}

Documentation

Index

Constants

View Source
const (
	// MethodDELETE is the HTTP DELETE method
	MethodDELETE = "DELETE"

	// MethodGET is the HTTP GET method
	MethodGET = "GET"

	// MethodHEAD is the HTTP HEAD method
	MethodHEAD = "HEAD"

	// MethodOPTIONS is the HTTP OPTIONS method
	MethodOPTIONS = "OPTIONS"

	// MethodPATCH is the HTTP PATCH method
	MethodPATCH = "PATCH"

	// MethodPOST is the HTTP POST method
	MethodPOST = "POST"

	// MethodPUT is the HTTP PUT method
	MethodPUT = "PUT"
)
View Source
const (
	// GET method
	GET = "GET"
	// HEAD method
	HEAD = "HEAD"
	// OPTIONS method
	OPTIONS = "OPTIONS"
	// POST method
	POST = "POST"
	// PUT method
	PUT = "PUT"
	// PATCH method
	PATCH = "PATCH"
	// DELETE method
	DELETE = "DELETE"
	// CONNECT method
	CONNECT = "CONNECT"

	// PathAny used to minimize memory allocations
	PathAny = "*"
	// PathSlashAny used to minimize memory allocations
	PathSlashAny = "/*"
	// PathSlash used to minimize memory allocations
	PathSlash = "/"

	// HeaderAllow used to minimize memory allocations
	HeaderAllow = "Allow"
)
View Source
const Slash = "/"

Slash constant used to minimize string allocations

View Source
const Version = "1.0.0"

Version gives you the gramework version you use now

Variables

View Source
var (
	// ErrTLSNoEmails occurs when no emails provided but user tries to use AutoTLS features
	ErrTLSNoEmails = errors.New("auto tls: no emails provided")

	// ErrArgNotFound used when no route argument is found
	ErrArgNotFound = errors.New("undefined argument")
)
View Source
var (
	// DefaultContentType cached to minimize memory allocations
	DefaultContentType = []byte("text/plain; charset=utf-8")
	// QuestionMark cached to minimize memory allocations
	QuestionMark = []byte("?")

	// SlashByte cached to minimize memory allocations
	SlashByte = byte('/')
)
View Source
var (
	// ErrEmptyMiddleware can be returned by App.Use*, if middleware is nil
	ErrEmptyMiddleware = errors.New("can't use nil middleware")

	// ErrUnsupportedMiddlewareType can be returned by App.Use*, if middleware type is unsupported
	ErrUnsupportedMiddlewareType = errors.New("unsupported middleware type")
)
View Source
var Logger = &log.Logger{
	Level:   log.InfoLevel,
	Handler: cli.New(os.Stdout),
}

Logger handles default logger

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

func Errorf

func Errorf(msg string, v ...interface{})

Errorf logs an error using default logger

func Nanotime

func Nanotime() int64

Nanotime is monotonic time provider.

func UnJSONBytes

func UnJSONBytes(b []byte, v ...interface{}) (interface{}, error)

UnJSONBytes serializes and writes a json-formatted response to user

Types

type App

type App struct {
	EnableFirewall bool

	Logger    log.Interface
	TLSEmails []string
	Settings  Settings

	HandleUnknownDomains bool

	Flags *Flags
	// contains filtered or unexported fields
}

App represents a gramework app

func New

func New() *App

New App

func (*App) AddFlag

func (app *App) AddFlag(f Flag)

AddFlag adds a Flag to flag queue that will be parsed if flags wasn't parsed yet

func (*App) CORSMiddleware

func (app *App) CORSMiddleware() func(*Context)

CORSMiddleware provides gramework handler with ctx.CORS() call

func (*App) DELETE

func (app *App) DELETE(route string, handler interface{}) *App

DELETE registers a handler for a DELETE request to the given route

func (*App) Domain

func (app *App) Domain(domain string) *Router

Domain returns a domain router

func (*App) Forbidden

func (app *App) Forbidden(ctx *Context)

Forbidden send 403 Forbidden error

func (*App) GET

func (app *App) GET(route string, handler interface{}) *App

GET registers a handler for a GET request to the given route

func (*App) HEAD

func (app *App) HEAD(route string, handler interface{}) *App

HEAD registers a handler for a HEAD request to the given route

func (*App) HTTP

func (app *App) HTTP() *Router

HTTP returns HTTP-only router

func (*App) HTTPS

func (app *App) HTTPS() *Router

HTTPS returns HTTPS-only router

func (*App) Handle

func (app *App) Handle(method, route string, handler interface{}) *App

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 (*App) HandleMethodNotAllowed

func (app *App) HandleMethodNotAllowed(newValue bool) (oldValue bool)

HandleMethodNotAllowed changes HandleMethodNotAllowed mode in the router

func (*App) HandleOPTIONS

func (app *App) HandleOPTIONS(newValue bool) (oldValue bool)

HandleOPTIONS changes HandleOPTIONS mode in the router

func (*App) Health

func (app *App) Health()

Health registers HealthHandler on /internal/health

func (*App) HealthHandler

func (app *App) HealthHandler(ctx *Context)

HealthHandler serves info about memory usage

func (*App) JSON

func (app *App) JSON(route string, handler interface{}) *App

JSON register internal handler that sets json content type and serves given handler with GET method

func (*App) ListenAndServe

func (app *App) ListenAndServe(addr ...string) error

ListenAndServe HTTP on given addr. runs flag.Parse() if !flag.Parsed() to support --bind flag.

func (*App) ListenAndServeAll

func (app *App) ListenAndServeAll(httpAddr ...string)

ListenAndServeAll serves HTTP and HTTPS automatically. HTTPS is served on :443. If it can't serve http or https, it logs an error and exit the server with app.Logger.Fatalf().

func (*App) ListenAndServeAllDev

func (app *App) ListenAndServeAllDev(httpAddr ...string)

ListenAndServeAllDev serves HTTP and HTTPS automatically with localhost HTTPS support via self-signed certs. HTTPS is served on :443. If it can't serve http or https, it logs an error and exit the server with app.Logger.Fatalf().

func (*App) ListenAndServeAutoTLS

func (app *App) ListenAndServeAutoTLS(addr string, cachePath ...string) error

ListenAndServeAutoTLS serves TLS requests

func (*App) ListenAndServeAutoTLSDev

func (app *App) ListenAndServeAutoTLSDev(addr string, cachePath ...string) error

ListenAndServeAutoTLSDev serves non-production grade TLS requests. Supports localhost.localdomain.

func (*App) MethodNotAllowed

func (app *App) MethodNotAllowed(c func(ctx *Context)) *App

MethodNotAllowed sets MethodNotAllowed handler

func (*App) NotFound

func (app *App) NotFound(notFoundHandler func(*Context)) *App

NotFound set a handler which is called when no matching route is found

func (*App) OPTIONS

func (app *App) OPTIONS(route string, handler interface{}) *App

OPTIONS registers a handler for a OPTIONS request to the given route

func (*App) PATCH

func (app *App) PATCH(route string, handler interface{}) *App

PATCH registers a handler for a PATCH request to the given route

func (*App) POST

func (app *App) POST(route string, handler interface{}) *App

POST registers a handler for a POST request to the given route

func (*App) PUT

func (app *App) PUT(route string, handler interface{}) *App

PUT registers a handler for a PUT request to the given route

func (*App) PanicHandler

func (app *App) PanicHandler(panicHandler func(*Context, interface{})) *App

PanicHandler set a handler for unhandled panics

func (*App) Redir

func (app *App) Redir(url string) func(*Context)

Redir sends 301 redirect to the given url

it's equivalent to

ctx.Redirect(url, 301)

func (*App) RegFlags

func (app *App) RegFlags()

RegFlags registers current flag queue in flag parser

func (*App) SPAIndex

func (app *App) SPAIndex(path string) *Router

SPAIndex serves an index file on any unregistered route

func (*App) Serve

func (app *App) Serve(ln net.Listener) error

Serve app on given listener

func (*App) ServeDir

func (app *App) ServeDir(path string) func(*Context)

ServeDir from a given path

func (*App) ServeDirCustom

func (app *App) ServeDirCustom(path string, stripSlashes int, compress bool, generateIndexPages bool, indexNames []string) func(*Context)

ServeDirCustom gives you ability to serve a dir with custom settings

func (*App) ServeDirNoCache

func (app *App) ServeDirNoCache(path string) func(*Context)

ServeDirNoCache gives you ability to serve a dir without caching

func (*App) ServeDirNoCacheCustom

func (app *App) ServeDirNoCacheCustom(path string, stripSlashes int, compress bool, generateIndexPages bool, indexNames []string) func(*Context)

ServeDirNoCacheCustom gives you ability to serve a dir with custom settings without caching

func (*App) ServeFile

func (app *App) ServeFile(route, file string) *Router

ServeFile serves a file on a given route

func (*App) ServeInfrastructure

func (app *App) ServeInfrastructure(i *infrastructure.Infrastructure)

ServeInfrastructure serves Infrastructure info It's an integration of our module

func (*App) Sub

func (app *App) Sub(path string) *SubRouter

Sub let you quickly register subroutes with given prefix like app.Sub("v1").Sub("users").GET("view/:id", "hi").DELETE("delete/:id", "hi"), that give you /v1/users/view/:id and /v1/users/delete/:id registered

func (*App) ToTLSHandler

func (app *App) ToTLSHandler() func(*Context)

ToTLSHandler returns handler that redirects user to HTTP scheme

func (*App) Use

func (app *App) Use(middleware interface{}) error

Use the middleware before request processing

func (*App) UseAfterRequest

func (app *App) UseAfterRequest(middleware interface{}) error

UseAfterRequest the middleware after request processing

func (*App) UsePre

func (app *App) UsePre(middleware interface{}) error

UsePre registers middleware before any other middleware. Use only for metrics or access control!

type Context

type Context struct {
	*fasthttp.RequestCtx

	Logger  log.Interface
	App     *App
	Cookies Cookies
	// contains filtered or unexported fields
}

Context is a gramework request context

func (*Context) CORS

func (c *Context) CORS() *Context

CORS enables CORS in the current context

func (*Context) Err500

func (c *Context) Err500(message ...interface{}) *Context

Err500 sets Internal Server Error status

func (*Context) Forbidden

func (c *Context) Forbidden()

Forbidden send 403 Forbidden error

func (*Context) GETKeys

func (c *Context) GETKeys() []string

GETKeys returns GET parameters keys

func (*Context) GETKeysBytes

func (c *Context) GETKeysBytes() [][]byte

GETKeysBytes returns GET parameters keys as []byte

func (*Context) GETParam

func (c *Context) GETParam(argName string) []string

func (*Context) GETParams

func (c *Context) GETParams() map[string][]string

GETParams returns GET parameters

func (*Context) HTML

func (c *Context) HTML() *Context

HTML sets HTML content type

func (*Context) JSON

func (c *Context) JSON(v interface{}) error

JSON serializes and writes a json-formatted response to user

func (*Context) JSONError

func (c *Context) JSONError(v interface{}) error

JSONError sets Internal Server Error status, serializes and writes a json-formatted response to user

func (*Context) LogHeaders

func (ctx *Context) LogHeaders()

func (*Context) Proxy

func (ctx *Context) Proxy(url string) error

Proxy request to given url

func (*Context) RouteArg

func (c *Context) RouteArg(argName string) string

RouteArg returns an argument value as a string or empty string

func (*Context) RouteArgErr

func (c *Context) RouteArgErr(argName string) (string, error)

RouteArgErr returns an argument value as a string or empty string and ErrArgNotFound if argument was not found

func (*Context) ToJSON

func (c *Context) ToJSON(v interface{}) ([]byte, error)

ToJSON serializes and returns the result

func (*Context) ToTLS

func (c *Context) ToTLS()

ToTLS redirects user to HTTPS scheme

func (*Context) UnJSON

func (c *Context) UnJSON(v interface{}) error

UnJSON deserializes JSON request body to given variable pointer

func (*Context) UnJSONBytes

func (c *Context) UnJSONBytes(b []byte, v ...interface{}) (interface{}, error)

UnJSONBytes serializes and writes a json-formatted response to user

func (*Context) Writef

func (c *Context) Writef(format string, a ...interface{})

Writef is a fmt.Fprintf(context, format, a...) shortcut

func (*Context) Writeln

func (c *Context) Writeln(a ...interface{})

Writeln is a fmt.Fprintln(context, format, a...) shortcut

type Cookies

type Cookies struct {
	Storage map[string]string
	Mu      sync.RWMutex
}

Cookies handles a typical cookie storage

func (*Cookies) Exists

func (c *Cookies) Exists(key string) bool

Exists reports if the given key exists for current request

func (*Cookies) Get

func (c *Cookies) Get(key string) (string, bool)

Get a cookie by given key

func (*Cookies) Set

func (c *Cookies) Set(key, value string)

Set a cookie with given key to the value

type FirewallSettings

type FirewallSettings struct {
	// MaxReqPerMin is a max request per minute count
	MaxReqPerMin int64
	// BlockTimeout in seconds
	BlockTimeout int64
}

FirewallSettings represents a new firewall settings. Internal firewall representation copies this settings atomically.

type Flag

type Flag struct {
	Name        string
	Description string
	Value       *string
	Default     string
}

Flag is a flag representation

type Flags

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

Flags is a flags storage

type RequestHandler

type RequestHandler func(*Context)

RequestHandler describes a standard request handler type

func NewGrameHandler

func NewGrameHandler(h http.Handler) RequestHandler

NewGrameHandler wraps net/http handler to fasthttp request handler, so it can be passed to fasthttp server.

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

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

This adaptor is a fork of https://github.com/valyala/fasthttp/tree/master/fasthttpadaptor We're embedding it because we don't want additional allocation, but we need exactly gramework request handler, not fasthttp request handler. The package provides helper functions for converting net/http request handlers to fasthttp request handlers. See the original license in /3rd-Party Licenses/fasthttp

func NewGrameHandlerFunc

func NewGrameHandlerFunc(h http.HandlerFunc) RequestHandler

NewGrameHandlerFunc wraps net/http handler func to gramework request handler, so it can be passed to gramework router.

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

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

This adaptor is a fork of https://github.com/valyala/fasthttp/tree/master/fasthttpadaptor We're embedding it because we don't want additional allocation, but we need exactly gramework request handler, not fasthttp request handler. The package provides helper functions for converting net/http request handlers to fasthttp request handlers. See the original license in /3rd-Party Licenses/fasthttp

type RequestHandlerErr

type RequestHandlerErr func(*Context) error

RequestHandlerErr describes a standard request handler with error returned type

type Router

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

Router handles internal handler conversion etc.

func (*Router) Allowed

func (r *Router) Allowed(path, reqMethod string) (allow string)

Allowed returns Allow header's value used in OPTIONS responses

func (*Router) DELETE

func (r *Router) DELETE(route string, handler interface{}) *Router

DELETE registers a handler for a DELETE request to the given route

func (*Router) Forbidden

func (r *Router) Forbidden(ctx *Context)

Forbidden serves 403 on route it registered on

func (*Router) GET

func (r *Router) GET(route string, handler interface{}) *Router

GET registers a handler for a GET request to the given route

func (*Router) HEAD

func (r *Router) HEAD(route string, handler interface{}) *Router

HEAD registers a handler for a HEAD request to the given route

func (*Router) HTTP

func (r *Router) HTTP() *Router

HTTP router returns a router instance that work only on HTTP requests

func (*Router) HTTPS

func (r *Router) HTTPS() *Router

HTTPS router returns a router instance that work only on HTTPS requests

func (*Router) Handle

func (r *Router) Handle(method, route string, handler interface{}) *Router

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

func (r *Router) HandleMethodNotAllowed(newValue bool) (oldValue bool)

HandleMethodNotAllowed changes HandleMethodNotAllowed mode in the router

func (*Router) HandleOPTIONS

func (r *Router) HandleOPTIONS(newValue bool) (oldValue bool)

HandleOPTIONS changes HandleOPTIONS mode in the router

func (*Router) Handler

func (r *Router) Handler() func(*Context)

Handler makes the router implement the fasthttp.ListenAndServe interface.

func (*Router) JSON

func (r *Router) JSON(route string, handler interface{}) *Router

JSON register internal handler that sets json content type and serves given handler with GET method

func (*Router) Lookup

func (r *Router) Lookup(method, path string, ctx *Context) (RequestHandler, 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) MethodNotAllowed

func (r *Router) MethodNotAllowed(c func(ctx *Context))

MethodNotAllowed sets MethodNotAllowed handler

func (*Router) NotFound

func (r *Router) NotFound(notFoundHandler func(*Context))

NotFound set a handler which is called when no matching route is found

func (*Router) OPTIONS

func (r *Router) OPTIONS(route string, handler interface{}) *Router

OPTIONS registers a handler for a OPTIONS request to the given route

func (*Router) PATCH

func (r *Router) PATCH(route string, handler interface{}) *Router

PATCH registers a handler for a PATCH request to the given route

func (*Router) POST

func (r *Router) POST(route string, handler interface{}) *Router

POST registers a handler for a POST request to the given route

func (*Router) PUT

func (r *Router) PUT(route string, handler interface{}) *Router

PUT registers a handler for a PUT request to the given route

func (*Router) PanicHandler

func (r *Router) PanicHandler(panicHandler func(*Context, interface{}))

PanicHandler set a handler for unhandled panics

func (*Router) Redir

func (r *Router) Redir(route, url string)

Redir sends 301 redirect to the given url

it's equivalent to

ctx.Redirect(url, 301)

func (*Router) SPAIndex

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

SPAIndex serves an index file on any unregistered route

func (*Router) ServeFile

func (r *Router) ServeFile(route, file string) *Router

ServeFile serves a file on a given route

func (*Router) ServeFiles

func (r *Router) ServeFiles(path string, rootPath string)

ServeFiles serves files from the given file system root. The path must end with "/*filepath", files are then served from the local path /defined/root/dir/*filepath. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler.

router.ServeFiles("/src/*filepath", "/var/www")

func (*Router) Sub

func (r *Router) Sub(path string) *SubRouter

Sub let you quickly register subroutes with given prefix like app.Sub("v1").GET("route", "hi"), that give you /v1/route registered

type Settings

type Settings struct {
	Firewall FirewallSettings
}

Settings for an App instance

type SubRouter

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

SubRouter handles subs registration like app.Sub("v1").GET("someRoute", "hi")

func (*SubRouter) DELETE

func (r *SubRouter) DELETE(route string, handler interface{}) *SubRouter

DELETE registers a handler for a DELETE request to the given route

func (*SubRouter) Forbidden

func (r *SubRouter) Forbidden(ctx *Context)

Forbidden is a shortcut for ctx.Forbidden

func (*SubRouter) GET

func (r *SubRouter) GET(route string, handler interface{}) *SubRouter

GET registers a handler for a GET request to the given route

func (*SubRouter) HEAD

func (r *SubRouter) HEAD(route string, handler interface{}) *SubRouter

HEAD registers a handler for a HEAD request to the given route

func (*SubRouter) HTTP

func (r *SubRouter) HTTP() *SubRouter

HTTP returns SubRouter for http requests with given r.prefix

func (*SubRouter) HTTPS

func (r *SubRouter) HTTPS() *SubRouter

HTTPS returns SubRouter for https requests with given r.prefix

func (*SubRouter) JSON

func (r *SubRouter) JSON(route string, handler interface{}) *SubRouter

JSON register internal handler that sets json content type and serves given handler with GET method

func (*SubRouter) OPTIONS

func (r *SubRouter) OPTIONS(route string, handler interface{}) *SubRouter

OPTIONS registers a handler for a OPTIONS request to the given route

func (*SubRouter) PATCH

func (r *SubRouter) PATCH(route string, handler interface{}) *SubRouter

PATCH registers a handler for a PATCH request to the given route

func (*SubRouter) POST

func (r *SubRouter) POST(route string, handler interface{}) *SubRouter

POST registers a handler for a POST request to the given route

func (*SubRouter) PUT

func (r *SubRouter) PUT(route string, handler interface{}) *SubRouter

PUT registers a handler for a PUT request to the given route

func (*SubRouter) Redir

func (r *SubRouter) Redir(route, url string)

Redir sends 301 redirect to the given url

it's equivalent to

ctx.Redirect(url, 301)

func (*SubRouter) ServeFile

func (r *SubRouter) ServeFile(route, file string) *SubRouter

ServeFile serves a file on a given route

func (*SubRouter) Sub

func (r *SubRouter) Sub(path string) *SubRouter

Sub let you quickly register subroutes with given prefix like app.Sub("v1").Sub("users").GET("view/:id", "hi").DELETE("delete/:id", "hi"), that give you /v1/users/view/:id and /v1/users/delete/:id registered

func (*SubRouter) ToTLSHandler

func (r *SubRouter) ToTLSHandler() func(*Context)

ToTLSHandler returns handler that redirects user to HTTP scheme

Directories

Path Synopsis
Package grypto provides helpers for dealing with cryptography
Package grypto provides helpers for dealing with cryptography

Jump to

Keyboard shortcuts

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