tigo

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2018 License: MIT Imports: 21 Imported by: 8

README

Tigo

GoDoc

Description

Tigo is a tiny framework for go, is forked from ozzo-routing which is a lightweight high performance HTTP request router, fast and powerful routing features for the high-performance. The package has the following features:

  • middleware pipeline architecture, similar to that of the Express framework.
  • extremely fast request routing with zero dynamic memory allocation
  • modular code organization through route grouping
  • flexible URL path matching, supporting URL parameters and regular expressions
  • URL creation according to the predefined routes

This fork adds the following features:

  • add OnError handdler for panic.
  • add render function for view(use html/template)
  • add panic middleware
  • add logger middleware
  • add static middleware
  • add more router functions.

Requirements

Go 1.7 or above.

Installation

Run the following command to install the package:

go get gopkg.in/foolin/tigo.v2

Or last version(developer):

go get github.com/foolin/tigo

Getting Started

Default example:

package main

import (
	"github.com/foolin/tigo"
	"log"
)

func main()  {

	router := tigo.Default()

	router.GET("/", func(ctx *tigo.Context) error {
		//out html
		return ctx.HTML(`
			Hello tigo!!!<hr>
			visit api: <a href="/api/tigo">api/tigo</a>
		`)
	})

	router.GET("/api/<action>", func(ctx *tigo.Context) error {
		//out json
		return ctx.JSON(tigo.M{
			"name": "tigo",
			"ip": ctx.RequestIP(),
			"action": ctx.Param("action"),
		})
	})

	//run
	log.Printf("run on :8080")
	err := router.Run(":8080")
	if err != nil {
		log.Fatalf("run error: %v", err)
	}
}
	
New example:

package main

import (
	"github.com/foolin/tigo"
	"os"
	"log"
)

func main()  {
	//new router
	router := tigo.New()

	//logger
	router.Use(tigo.Logger(os.Stdout))

	//panic
	router.Use(tigo.Panic(os.Stderr))

	//register router
	router.GET("/", func(ctx *tigo.Context) error {
		return ctx.HTML("Hello tigo!!!")
	})

	//run
	log.Printf("run on :8080")
	err := router.Run(":8080")
	if err != nil {
		log.Fatalf("run error: %v", err)
	}
}

Render example:

Use context.Render()


package main

import (
	"github.com/foolin/tigo"
	"log"
	"html/template"
)

func main() {

	//new router
	router := tigo.New()

	//set render, tigo.Default() will default initialize.
	router.Render = tigo.NewViewRender(tigo.ViewRenderConfig{
		Root: "views",
		Extension: ".html",
		Master: "layout/master",
		Partials: []string{"layout/footer"},
		Funcs: template.FuncMap{
			"echo": func(content string) template.HTML {
				return template.HTML(content)
			},
		},
		DisableCache: false,
		DisableFilePartial: false,
	})

	//register router
	router.GET("/", func(ctx *tigo.Context) error {
		return ctx.Render("index", tigo.M{
			"title": "Index title!",
			"escape": func(content string) string {
				return template.HTMLEscapeString(content)
			},
		})
	})

	router.GET("/page_file", func(ctx *tigo.Context) error {
		return ctx.RenderFile("page_file", tigo.M{"title": "Page file title!!"})
	})

	//run
	log.Printf("run on :8080")
	err := router.Run(":8080")
	if err != nil {
		log.Fatalf("run error: %v", err)
	}
}
	

/views/layout/master.html

    <!-- /views/admin/master.html -->
    
    <!doctype html>
    
    <html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <title>{{.title}}</title>
        {{template "head" .}}
    </head>
    
    <body>
    admin/master.html
    
    <hr>
    render page content will at here:
    {{template "content" .}}
    
    {{include "layout/footer"}}
    </body>
    </html>
        

/views/layout/footer.html

    <!-- /views/layout/footer.html -->
    Copyright &copy2016 by <a href="https://github.com/foolin/tigo">tigo</a>.

/views/index.html

    {{define "head"}}
        <style>
            .hello{ color: red;}
            hr{ border: 1px #ccc dashed;}
        </style>
    {{end}}
    
    
    {{define "content"}}
        <h1 class="hello">This is content!!!!</h1>
        {{echo `<!-- echo function out, you can see it at source! -->`}}
        {{call $.escape `<!-- Hello world-->`}}
        <hr>
        <p><a href="/page_file">page file</a></p>
    {{end}}

/views/page_file.html

    <!-- /views/page_file.html -->
    <!doctype html>
    
    <html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <title>{{.title}}</title>
    </head>
    
    <body>
    <a href="/"><- Back home!</a>
    <hr>
    
    page.html
    {{include "layout/footer"}}
    </body>
    </html>

Now run the following command to start the Web server:

go run main.go

You should be able to access URLs such as http://localhost:8080.

Routes

tigo works by building a routing table in a router and then dispatching HTTP requests to the matching handlers found in the routing table. An intuitive illustration of a routing table is as follows:

Routes Handlers
GET /users m1, m2, h1, ...
POST /users m1, m2, h2, ...
PUT /users/<id> m1, m2, h3, ...
DELETE /users/<id> m1, m2, h4, ...

For an incoming request GET /users, the first route would match and the handlers m1, m2, and h1 would be executed. If the request is PUT /users/123, the third route would match and the corresponding handlers would be executed. Note that the token <id> can match any number of non-slash characters and the matching part can be accessed as a path parameter value in the handlers.

If an incoming request matches multiple routes in the table, the route added first to the table will take precedence. All other matching routes will be ignored.

The actual implementation of the routing table uses a variant of the radix tree data structure, which makes the routing process as fast as working with a hash table, thanks to the inspiration from httprouter.

To add a new route and its handlers to the routing table, call the To method like the following:

router := tigo.New()
router.To("GET", "/users", m1, m2, h1)
router.To("POST", "/users", m1, m2, h2)

You can also use shortcut methods, such as Get, Post, Put, etc., which are named after the HTTP method names:

router.Get("/users", m1, m2, h1)
router.Post("/users", m1, m2, h2)

If you have multiple routes with the same URL path but different HTTP methods, like the above example, you can chain them together as follows,

router.Get("/users", m1, m2, h1).Post(m1, m2, h2)

If you want to use the same set of handlers to handle the same URL path but different HTTP methods, you can take the following shortcut:

router.To("GET,POST", "/users", m1, m2, h)

A route may contain parameter tokens which are in the format of <name:pattern>, where name stands for the parameter name, and pattern is a regular expression which the parameter value should match. A token <name> is equivalent to <name:[^/]*>, i.e., it matches any number of non-slash characters. At the end of a route, an asterisk character can be used to match any number of arbitrary characters. Below are some examples:

  • /users/<username>: matches /users/admin
  • /users/accnt-<id:\d+>: matches /users/accnt-123, but not /users/accnt-admin
  • /users/api<id:.*>: matches /users/api-abc, /users/api/list/page/1
  • /users/<username>/*: matches /users/admin/profile/address

When a URL path matches a route, the matching parameters on the URL path can be accessed via Context.Param():

router := tigo.New()

router.Get("/users/<username>", func (c *tigo.Context) error {
	fmt.Fprintf(c, "Name: %v", c.Param("username"))
	return nil
})
Route Groups

Route group is a way of grouping together the routes which have the same route prefix. The routes in a group also share the same handlers that are registered with the group via its Use method. For example,

router := tigo.New()
api := router.Group("/api")
api.Use(m1, m2)
api.Get("/users", h1).Post(h2)
api.Put("/users/<id>", h3).Delete(h4)

The above /api route group establishes the following tigo table:

Routes Handlers
GET /api/users m1, m2, h1, ...
POST /api/users m1, m2, h2, ...
PUT /api/users/<id> m1, m2, h3, ...
DELETE /api/users/<id> m1, m2, h4, ...

As you can see, all these routes have the same route prefix /api and the handlers m1 and m2. In other similar tigo frameworks, the handlers registered with a route group are also called middlewares.

Route groups can be nested. That is, a route group can create a child group by calling the Group() method. The router serves as the top level route group. A child group inherits the handlers registered with its parent group. For example,

router := tigo.New()
router.Use(m1)

api := router.Group("/api")
api.Use(m2)

users := group.Group("/users")
users.Use(m3)
users.Put("/<id>", h1)

Because the router serves as the parent of the api group which is the parent of the users group, the PUT /api/users/<id> route is associated with the handlers m1, m2, m3, and h1.

Router

Router manages the tigo table and dispatches incoming requests to appropriate handlers. A router instance is created by calling the tigo.New() method.

To hook up router with fasthttp, use the following code:

router := tigo.New()
fasthttp.ListenAndServe(":8080", router.HandleRequest) 
Handlers

A handler is a function with the signature func(*tigo.Context) error. A handler is executed by the router if the incoming request URL path matches the route that the handler is associated with. Through the tigo.Context parameter, you can access the request information in handlers.

A route may be associated with multiple handlers. These handlers will be executed in the order that they are registered to the route. The execution sequence can be terminated in the middle using one of the following two methods:

  • A handler returns an error: the router will skip the rest of the handlers and handle the returned error.
  • A handler calls Context.Abort(): the router will simply skip the rest of the handlers. There is no error to be handled.

A handler can call Context.Next() to explicitly execute the rest of the unexecuted handlers and take actions after they finish execution. For example, a response compression handler may start the output buffer, call Context.Next(), and then compress and send the output to response.

Context

For each incoming request, a tigo.Context object is passed through the relevant handlers. Because tigo.Context embeds fasthttp.RequestCtx, you can access all properties and methods provided by the latter.

Additionally, the Context.Param() method allows handlers to access the URL path parameters that match the current route. Using Context.Get() and Context.Set(), handlers can share data between each other. For example, an authentication handler can store the authenticated user identity by calling Context.Set(), and other handlers can retrieve back the identity information by calling Context.Get().

Context also provides a handy WriteData() method that can be used to write data of arbitrary type to the response. The WriteData() method can also be overridden (by replacement) to achieve more versatile response data writing.

Error Handling

A handler may return an error indicating some erroneous condition. Sometimes, a handler or the code it calls may cause a panic. Both should be handled properly to ensure best user experience. It is recommended that you use the fault.Recover handler or a similar error handler to handle these errors.

If an error is not handled by any handler, the router will handle it by calling its handleError() method which simply sets an appropriate HTTP status code and writes the error message to the response.

When an incoming request has no matching route, the router will call the handlers registered via the Router.NotFound() method. All the handlers registered via Router.Use() will also be called in advance. By default, the following two handlers are registered with Router.NotFound():

  • tigo.MethodNotAllowedHandler: a handler that sends an Allow HTTP header indicating the allowed HTTP methods for a requested URL
  • tigo.NotFoundHandler: a handler triggering 404 HTTP error

Version

!!! Important, current is v2, v1 is fork Fasthttp-routing, but v2 is fork ozzo-routing. if you use v1 version, please use this:

go get gopkg.in/foolin/tigo.v1

Docs

See http://godoc.org/github.com/foolin/tigo .

Documentation

Overview

Package routing provides high performance and powerful HTTP routing capabilities.

Example
router := routing.New()

router.Use(
	// all these handlers are shared by every route
	access.Logger(log.Printf),
	slash.Remover(http.StatusMovedPermanently),
	fault.Recovery(log.Printf),
)

// serve RESTful APIs
api := router.Group("/api")
api.Use(
	// these handlers are shared by the routes in the api group only
	content.TypeNegotiator(content.JSON, content.XML),
)
api.Get("/users", func(c *routing.Context) error {
	return c.Write("user list")
})
api.Post("/users", func(c *routing.Context) error {
	return c.Write("create a new user")
})
api.Put(`/users/<id:\d+>`, func(c *routing.Context) error {
	return c.Write("update user " + c.Param("id"))
})

// serve index file
router.Get("/", file.Content("ui/list.html"))
// serve files under the "ui" subdirectory
router.Get("/*", file.Server(file.PathMap{
	"/": "/ui/",
}))

http.Handle("/", router)
http.ListenAndServe(":8080", nil)
Output:

Index

Examples

Constants

View Source
const (
	MIME_JSON           = "application/json"
	MIME_XML            = "application/xml"
	MIME_XML2           = "text/xml"
	MIME_HTML           = "text/html"
	MIME_FORM           = "application/x-www-form-urlencoded"
	MIME_MULTIPART_FORM = "multipart/form-data"
)

MIME types used when doing request data reading and response data writing.

Variables

View Source
var Methods = []string{
	"CONNECT",
	"DELETE",
	"GET",
	"HEAD",
	"OPTIONS",
	"PATCH",
	"POST",
	"PUT",
	"TRACE",
}

Methods lists all supported HTTP methods by Router.

Functions

func MethodNotAllowedHandler

func MethodNotAllowedHandler(c *Context) error

MethodNotAllowedHandler handles the situation when a request has matching route without matching HTTP method. In this case, the handler will respond with an Allow HTTP header listing the allowed HTTP methods. Otherwise, the handler will do nothing and let the next handler (usually a NotFoundHandler) to handle the problem.

func NotFoundHandler

func NotFoundHandler(*Context) error

NotFoundHandler returns a 404 HTTP error indicating a request has no matching route.

func ReadFormData

func ReadFormData(form map[string][]string, data interface{}) error

ReadFormData populates the data variable with the data from the given form values.

Types

type Context

type Context struct {
	Request  *http.Request       // the current request
	Response http.ResponseWriter // the response writer
	// contains filtered or unexported fields
}

Context represents the contextual data and environment while processing an incoming HTTP request.

func NewContext

func NewContext(res http.ResponseWriter, req *http.Request, handlers ...Handler) *Context

NewContext creates a new Context object with the given response, request, and the handlers. This method is primarily provided for writing unit tests for handlers.

func (*Context) Abort

func (c *Context) Abort()

Abort skips the rest of the handlers associated with the current route. Abort is normally used when a handler handles the request normally and wants to skip the rest of the handlers. If a handler wants to indicate an error condition, it should simply return the error without calling Abort.

func (*Context) DelCookie

func (c *Context) DelCookie(name string)

func (*Context) Error

func (c *Context) Error(err error)

func (*Context) Form

func (c *Context) Form(key string, defaultValue ...string) string

Form returns the first value for the named component of the query. Form reads the value from POST and PUT body parameters as well as URL query parameters. The form takes precedence over the latter. If key is not present, it returns the specified default value or an empty string.

func (*Context) Get

func (c *Context) Get(name string) interface{}

Get returns the named data item previously registered with the context by calling Set. If the named data item cannot be found, nil will be returned.

func (*Context) GetCookieValue

func (c *Context) GetCookieValue(name string) string

func (*Context) HTML

func (c *Context) HTML(content string) error

HTML writes HTML values to the response.

func (*Context) IsAjax

func (c *Context) IsAjax() bool

IsAjax returns true if this request is an 'ajax request'( XMLHttpRequest)

Read more at: http://www.w3schools.com/ajax/

func (*Context) IsGet

func (c *Context) IsGet() bool

func (*Context) IsPost

func (c *Context) IsPost() bool

func (*Context) JSON

func (c *Context) JSON(data interface{}) (err error)

JSON writes json values to the response.

func (*Context) Next

func (c *Context) Next() error

Next calls the rest of the handlers associated with the current route. If any of these handlers returns an error, Next will return the error and skip the following handlers. Next is normally used when a handler needs to do some postprocessing after the rest of the handlers are executed.

func (*Context) Param

func (c *Context) Param(name string) string

Param returns the named parameter value that is found in the URL path matching the current route. If the named parameter cannot be found, an empty string will be returned.

func (*Context) PostForm

func (c *Context) PostForm(key string, defaultValue ...string) string

PostForm returns the first value for the named component from POST and PUT body parameters. If key is not present, it returns the specified default value or an empty string.

func (*Context) Query

func (c *Context) Query(name string, defaultValue ...string) string

Query returns the first value for the named component of the URL query parameters. If key is not present, it returns the specified default value or an empty string.

func (*Context) Read

func (c *Context) Read(data interface{}) error

Read populates the given struct variable with the data from the current request. If the request is NOT a GET request, it will check the "Content-Type" header and find a matching reader from DataReaders to read the request data. If there is no match or if the request is a GET request, it will use DefaultFormDataReader to read the request data.

func (*Context) Redirect

func (c *Context) Redirect(uri string)

func (*Context) Render

func (c *Context) Render(name string, data interface{}) error

Render render with master

func (*Context) RenderFile

func (c *Context) RenderFile(name string, data interface{}) error

Render render only file

func (*Context) RequestBody

func (c *Context) RequestBody() ([]byte, error)

Get Request body value

func (*Context) RequestIP

func (c *Context) RequestIP() string

ClientIp client ip

func (*Context) Router

func (c *Context) Router() *Router

Router returns the Router that is handling the incoming HTTP request.

func (*Context) Set

func (c *Context) Set(name string, value interface{})

Set stores the named data item in the context so that it can be retrieved later.

func (*Context) SetCookieValue

func (c *Context) SetCookieValue(name string, value string, expire time.Time)

func (*Context) SetDataWriter

func (c *Context) SetDataWriter(writer DataWriter)

SetDataWriter sets the data writer that will be used by Write().

func (*Context) SetParam

func (c *Context) SetParam(name, value string)

SetParam sets the named parameter value. This method is primarily provided for writing unit tests.

func (*Context) Text

func (c *Context) Text(content string) error

Text writes text values to the response.

func (*Context) URL

func (c *Context) URL(route string, pairs ...interface{}) string

URL creates a URL using the named route and the parameter values. The parameters should be given in the sequence of name1, value1, name2, value2, and so on. If a parameter in the route is not provided a value, the parameter token will remain in the resulting URL. Parameter values will be properly URL encoded. The method returns an empty string if the URL creation fails.

func (*Context) Write

func (c *Context) Write(data interface{}) error

Write writes the given data of arbitrary type to the response. The method calls the data writer set via SetDataWriter() to do the actual writing. By default, the DefaultDataWriter will be used.

type DataReader

type DataReader interface {
	// Read reads from the given HTTP request and populate the specified data.
	Read(*http.Request, interface{}) error
}

DataReader is used by Context.Read() to read data from an HTTP request.

var (
	// DataReaders lists all supported content types and the corresponding data readers.
	// Context.Read() will choose a matching reader from this list according to the "Content-Type"
	// header from the current request.
	// You may modify this variable to add new supported content types.
	DataReaders = map[string]DataReader{
		MIME_FORM:           &FormDataReader{},
		MIME_MULTIPART_FORM: &FormDataReader{},
		MIME_JSON:           &JSONDataReader{},
		MIME_XML:            &XMLDataReader{},
		MIME_XML2:           &XMLDataReader{},
	}
	// DefaultFormDataReader is the reader used when there is no matching reader in DataReaders
	// or if the current request is a GET request.
	DefaultFormDataReader DataReader = &FormDataReader{}
)

type DataWriter

type DataWriter interface {
	// SetHeader sets necessary response headers.
	SetHeader(http.ResponseWriter)
	// Write writes the given data into the response.
	Write(http.ResponseWriter, interface{}) error
}

DataWriter is used by Context.Write() to write arbitrary data into an HTTP response.

var DefaultDataWriter DataWriter = &dataWriter{}

DefaultDataWriter writes the given data in an HTTP response. If the data is neither string nor byte array, it will use fmt.Fprint() to write it into the response.

type ErrorHandler

type ErrorHandler func(*Context, error)

ErrorHandler is function for handling error.

type FormDataReader

type FormDataReader struct{}

FormDataReader reads the query parameters and request body as form data.

func (*FormDataReader) Read

func (r *FormDataReader) Read(req *http.Request, data interface{}) error

type HTTPError

type HTTPError interface {
	error
	// StatusCode returns the HTTP status code of the error
	StatusCode() int
}

HTTPError represents an HTTP error with HTTP status code and error message

func NewHTTPError

func NewHTTPError(status int, message ...string) HTTPError

NewHTTPError creates a new HttpError instance. If the error message is not given, http.StatusText() will be called to generate the message based on the status code.

type Handler

type Handler func(*Context) error

Handler is the function for handling HTTP requests.

func HTTPHandler

func HTTPHandler(h http.Handler) Handler

HTTPHandler adapts a http.Handler into a routing.Handler.

func HTTPHandlerFunc

func HTTPHandlerFunc(h http.HandlerFunc) Handler

HTTPHandlerFunc adapts a http.HandlerFunc into a routing.Handler.

func Logger

func Logger(writer io.Writer) Handler

func Panic

func Panic(writer io.Writer) Handler

type JSONDataReader

type JSONDataReader struct{}

JSONDataReader reads the request body as JSON-formatted data.

func (*JSONDataReader) Read

func (r *JSONDataReader) Read(req *http.Request, data interface{}) error

type LogResponseWriter

type LogResponseWriter struct {
	http.ResponseWriter
	Status       int
	BytesWritten int64
}

LogResponseWriter wraps http.ResponseWriter in order to capture HTTP status and response length information.

func (*LogResponseWriter) Write

func (r *LogResponseWriter) Write(p []byte) (int, error)

func (*LogResponseWriter) WriteHeader

func (r *LogResponseWriter) WriteHeader(status int)

type M

type M map[string]interface{}

Map for data with map[string]interface{}

type Render

type Render interface {
	//Init
	Init() error
	//Render layout and name
	Render(out io.Writer, name string, data interface{}) error
	//Render only file.
	RenderFile(out io.Writer, name string, data interface{}) error
}

type Route

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

Route represents a URL path pattern that can be used to match requested URLs.

func (*Route) Connect

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

Connect adds the route to the router using the CONNECT HTTP method.

func (*Route) Delete

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

Delete adds the route to the router using the DELETE HTTP method.

func (*Route) Get

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

Get adds the route to the router using the GET HTTP method.

func (*Route) Head

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

Head adds the route to the router using the HEAD HTTP method.

func (*Route) Method

func (r *Route) Method() string

Method returns the HTTP method that this route is associated with.

func (*Route) Name

func (r *Route) Name(name string) *Route

Name sets the name of the route. This method will update the registration of the route in the router as well.

func (*Route) Options

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

Options adds the route to the router using the OPTIONS HTTP method.

func (*Route) Patch

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

Patch adds the route to the router using the PATCH HTTP method.

func (*Route) Path

func (r *Route) Path() string

Path returns the request path that this route should match.

func (*Route) Post

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

Post adds the route to the router using the POST HTTP method.

func (*Route) Put

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

Put adds the route to the router using the PUT HTTP method.

func (*Route) String

func (r *Route) String() string

String returns the string representation of the route.

func (*Route) Tag

func (r *Route) Tag(value interface{}) *Route

Tag associates some custom data with the route.

func (*Route) Tags

func (r *Route) Tags() []interface{}

Tags returns all custom data associated with the route.

func (*Route) To

func (r *Route) To(methods string, handlers ...Handler) *Route

To adds the route to the router with the given HTTP methods and handlers. Multiple HTTP methods should be separated by commas (without any surrounding spaces).

func (*Route) Trace

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

Trace adds the route to the router using the TRACE HTTP method.

func (*Route) URL

func (r *Route) URL(pairs ...interface{}) (s string)

URL creates a URL using the current route and the given parameters. The parameters should be given in the sequence of name1, value1, name2, value2, and so on. If a parameter in the route is not provided a value, the parameter token will remain in the resulting URL. The method will perform URL encoding for all given parameter values.

type RouteGroup

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

RouteGroup represents a group of routes that share the same path prefix.

func (*RouteGroup) Any

func (rg *RouteGroup) Any(path string, handlers ...Handler) *Route

Any adds a route with the given route, handlers, and the HTTP methods as listed in routing.Methods.

func (*RouteGroup) CONNECT

func (rg *RouteGroup) CONNECT(path string, handlers ...Handler) *Route

Connect adds a CONNECT route to the router with the given route path and handlers.

func (*RouteGroup) DELETE

func (rg *RouteGroup) DELETE(path string, handlers ...Handler) *Route

Delete adds a DELETE route to the router with the given route path and handlers.

func (*RouteGroup) File

func (rg *RouteGroup) File(path string, filePath string) *Route

Content returns a handler that serves the content of the specified file as the response. The file to be served can be specified as an absolute file path or a path relative to RootPath (which defaults to the current working path). If the specified file does not exist, the handler will pass the control to the next available handler.

func (*RouteGroup) GET

func (rg *RouteGroup) GET(path string, handlers ...Handler) *Route

Get adds a GET route to the router with the given route path and handlers.

func (*RouteGroup) Group

func (rg *RouteGroup) Group(prefix string, handlers ...Handler) *RouteGroup

Group creates a RouteGroup with the given route path prefix and handlers. The new group will combine the existing path prefix with the new one. If no handler is provided, the new group will inherit the handlers registered with the current group.

func (*RouteGroup) HEAD

func (rg *RouteGroup) HEAD(path string, handlers ...Handler) *Route

Head adds a HEAD route to the router with the given route path and handlers.

func (*RouteGroup) OPTIONS

func (rg *RouteGroup) OPTIONS(path string, handlers ...Handler) *Route

Options adds an OPTIONS route to the router with the given route path and handlers.

func (*RouteGroup) PATCH

func (rg *RouteGroup) PATCH(path string, handlers ...Handler) *Route

Patch adds a PATCH route to the router with the given route path and handlers.

func (*RouteGroup) POST

func (rg *RouteGroup) POST(path string, handlers ...Handler) *Route

Post adds a POST route to the router with the given route path and handlers.

func (*RouteGroup) PUT

func (rg *RouteGroup) PUT(path string, handlers ...Handler) *Route

Put adds a PUT route to the router with the given route path and handlers.

func (*RouteGroup) Static

func (rg *RouteGroup) Static(path string, dir string) *Route

Content returns a handler that serves the content of the specified file as the response. The file to be served can be specified as an absolute file path or a path relative to RootPath (which defaults to the current working path). If the specified file does not exist, the handler will pass the control to the next available handler.

func (*RouteGroup) TRACE

func (rg *RouteGroup) TRACE(path string, handlers ...Handler) *Route

Trace adds a TRACE route to the router with the given route path and handlers.

func (*RouteGroup) To

func (rg *RouteGroup) To(methods, path string, handlers ...Handler) *Route

To adds a route to the router with the given HTTP methods, route path, and handlers. Multiple HTTP methods should be separated by commas (without any surrounding spaces).

func (*RouteGroup) Use

func (rg *RouteGroup) Use(handlers ...Handler)

Use registers one or multiple handlers to the current route group. These handlers will be shared by all routes belong to this group and its subgroups.

type Router

type Router struct {
	RouteGroup
	Render              Render
	OnError             ErrorHandler
	IgnoreTrailingSlash bool // whether to ignore trailing slashes in the end of the request URL
	// contains filtered or unexported fields
}

Router manages routes and dispatches HTTP requests to the handlers of the matching routes.

func Default

func Default() *Router

Default create default router, use panic, logger and render.

func New

func New() *Router

New creates a new Router object.

func (*Router) NotFound

func (r *Router) NotFound(handlers ...Handler)

NotFound specifies the handlers that should be invoked when the router cannot find any route matching a request. Note that the handlers registered via Use will be invoked first in this case.

func (*Router) Route

func (r *Router) Route(name string) *Route

Route returns the named route. Nil is returned if the named route cannot be found.

func (*Router) Routes

func (r *Router) Routes() []*Route

Routes returns all routes managed by the router.

func (*Router) Run

func (r *Router) Run(addr string) error

func (*Router) ServeHTTP

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

ServeHTTP handles the HTTP request. It is required by http.Handler

func (*Router) Use

func (r *Router) Use(handlers ...Handler)

Use appends the specified handlers to the router and shares them with all routes.

type ViewRender

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

func NewViewRender

func NewViewRender(config ViewRenderConfig) *ViewRender

func (*ViewRender) Init

func (r *ViewRender) Init() error

func (*ViewRender) Render

func (r *ViewRender) Render(out io.Writer, name string, data interface{}) error

Render a template to the screen

func (*ViewRender) RenderFile

func (r *ViewRender) RenderFile(out io.Writer, name string, data interface{}) error

Render a template to the screen

type ViewRenderConfig

type ViewRenderConfig struct {
	Root               string           //view root
	Extension          string           //template extension
	Master             string           //template master
	Partials           []string         //template partial, such as head, foot
	Funcs              template.FuncMap //template functions
	DisableCache       bool             //disable cache, debug mode
	DisableFilePartial bool             //enable render file use partial
}

type XMLDataReader

type XMLDataReader struct{}

XMLDataReader reads the request body as XML-formatted data.

func (*XMLDataReader) Read

func (r *XMLDataReader) Read(req *http.Request, data interface{}) error

Directories

Path Synopsis
examples
new

Jump to

Keyboard shortcuts

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