makross

package module
v0.0.0-...-10dc113 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2017 License: MIT Imports: 30 Imported by: 10

README

Makross

Package makross is a high productive and modular web framework in Golang.

Description

Makross is a Go package that provides high performance and powerful HTTP makross capabilities for Web applications. Makross is very fast, thanks to the radix tree data structure and the usage of sync.Pool

It has the following features:

  • middleware pipeline architecture, similar to that of the Express framework.
  • extremely fast request makross with zero dynamic memory allocation (the performance is comparable to that of httprouter and gin)
  • modular code organization through route grouping
  • flexible URL path matching, supporting URL parameters and regular expressions
  • URL creation according to the predefined routes
  • compatible with http.Handler and http.HandlerFunc
  • ready-to-use handlers sufficient for building RESTful APIs

If you are using fasthttp, you may use a similar makross package macross which is adapted from Makross.

Requirements

Go 1.9 or above.

Installation

Run the following command to install the package:

go get github.com/insionng/makross

Getting Started

Create a server.go file with the following content:

package main

import (
	"github.com/insionng/makross"
)

func main() {
	m := makross.New()
	
	m.Get("/", func(self *makross.Context) error {
		return self.String("Hello, Makross")
	})

	m.Listen(9000)
}

Now run the following command to start the Web server:

go run server.go

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

Getting Started via JWT

package main

import (
	"fmt"
	"github.com/insionng/makross"
	"github.com/insionng/makross/cors"
	"github.com/insionng/makross/jwt"
	"github.com/insionng/makross/logger"
	"github.com/insionng/makross/recover"
	"time"
)

/*
curl -I -X GET http://localhost:9000/jwt/get/ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOjEsImV4cCI6MTQ3OTQ4NDUzOH0.amQOtO0GESwLoevaGSoR55jCUqZ6vsIi9DPTkDh4tSk"
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0    26    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0HTTP/1.1 200 OK
Server: Makross
Date: Fri, 18 Nov 2016 15:55:18 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 26
Vary: Origin
Access-Control-Allow-Origin: *
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOjEsImV4cCI6MTQ3OTQ4NDU3OH0.KBTm7A3xqWmQ6NLfUecfowgszfKzwMrjO3k0gf8llc8
*/

func main() {
	m := makross.New()
	m.Use(logger.Logger())
	m.Use(recover.Recover())
	m.Use(cors.CORS())

	m.Get("/", func(self *makross.Context) error {
		fmt.Println(self.Response.Header.String())
		var data = map[string]interface{}{}
		data["version"] = "1.0.0"
		return self.JSON(data)
	})

	var secret = "secret"
	var exprires = time.Minute * 1
	// 给用户返回token之前请先密码验证用户身份
	m.Post("/signin/", func(self *makross.Context) error {

		fmt.Println(self.Response.String())

		username := self.Args("username").String()
		password := self.Args("password").String()
		if (username == "insion") && (password == "PaSsworD") {
			claims := jwt.NewMapClaims()
			claims["UserId"] = 1
			claims["exp"] = time.Now().Add(exprires).Unix()

			tk, _ := jwt.NewTokenString(secret, "HS256", claims)

			var data = map[string]interface{}{}
			data["token"] = tk

			return self.JSON(data)
		}

		herr := new(makross.HTTPError)
		herr.Message = "ErrUnauthorized"
		herr.Status = makross.StatusUnauthorized
		return self.JSON(herr, makross.StatusUnauthorized)

	})

	g := m.Group("/jwt", jwt.JWT(secret))
	// http://localhost:9000/jwt/get/
	g.Get("/get/", func(self *makross.Context) error {

		var data = map[string]interface{}{}

		claims := jwt.GetMapClaims(self)
		jwtUserId := claims["UserId"].(float64)
		fmt.Println(jwtUserId)
		exp := int64(claims["exp"].(float64))
		exptime := time.Unix(exp, 0).Sub(time.Now())

		if (exptime > 0) && (exptime < (exprires / 3)) {
			fmt.Println("exptime will be expires")
			claims["UserId"] = 1
			claims["exp"] = time.Now().Add(exprires).Unix()

			token := jwt.NewToken("HS256", claims)
			tokenString, _ := token.SignedString([]byte(secret))

			self.Response.Header.Set(makross.HeaderAccessControlExposeHeaders, "Authorization")
			self.Response.Header.Set("Authorization", jwt.Bearer+" "+tokenString)
			self.Set(jwt.DefaultJWTConfig.ContextKey, token)
		}

		data["value"] = "Hello, Makross"
		return self.JSON(data)
	})

	m.Listen(9000)
}

Getting Started via Session

package main

import (
	"github.com/insionng/makross"
	"github.com/insionng/makross/recover"
	"github.com/insionng/makross/session"
	_ "github.com/insionng/makross/session/redis"
	"log"
)

func main() {

	v := makross.New()
	v.Use(recover.Recover())
	//v.Use(session.Sessioner(session.Options{"file", `{"cookieName":"MakrossSessionId","gcLifetime":3600,"providerConfig":"./data/session"}`}))
	v.Use(session.Sessioner(session.Options{"redis", `{"cookieName":"MakrossSessionId","gcLifetime":3600,"providerConfig":"127.0.0.1:6379"}`}))

	v.Get("/get", func(self *makross.Context) error {
		value := "nil"
		valueIf := self.Session.Get("key")
		if valueIf != nil {
			value = valueIf.(string)
		}

		return self.String(value)

	})

	v.Get("/set", func(self *makross.Context) error {

		val := self.QueryParam("v")
		if len(val) == 0 {
			val = "value"
		}

		err := self.Session.Set("key", val)
		if err != nil {
			log.Printf("sess.set %v \n", err)
		}
		return self.String("okay")
	})

	v.Listen(7777)
}

Getting Started via i18n

package main

import (
	"fmt"
	"github.com/insionng/makross"
	"github.com/insionng/makross/i18n"
)

func main() {
	m := makross.New()
	m.Use(i18n.I18n(i18n.Options{
		Directory:   "locale",
		DefaultLang: "zh-CN",
		Langs:       []string{"en-US", "zh-CN"},
		Names:       []string{"English", "简体中文"},
		Redirect:    true,
	}))

	m.Get("/", func(self *makross.Context) error {
		fmt.Println("Header>", self.Request.Header.String())
		return self.String("current language is " + self.Language())
	})

	// Use in handler.
	m.Get("/trans", func(self *makross.Context) error {
		fmt.Println("Header>", self.Request.Header.String())
		return self.String(fmt.Sprintf("hello %s", self.Tr("world")))
	})

	fmt.Println("Listen on 9999")
	m.Listen(9999)
}

Getting Started via Go template

package main

import (
	"github.com/insionng/makross"
	"github.com/insionng/makross/gonder"
	"github.com/insionng/makross/logger"
	"github.com/insionng/makross/recover"
	"github.com/insionng/makross/static"
)

func main() {
	v := makross.New()
	v.Use(logger.Logger())
	v.Use(recover.Recover())
	v.SetRenderer(gonder.Renderor())
	v.Use(static.Static("static"))
	v.Get("/", func(self *makross.Context) error {
		var data = make(map[string]interface{})
		data["name"] = "Insion Ng"
		self.SetStore(data)

		self.SetStore(map[string]interface{}{
			"title": "你好,世界",
			"oh":    "no",
		})
		self.Set("oh", "yes") //覆盖前面指定KEY
		return self.Render("index")
	})

	v.Listen(":9000")
}

templates/index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="/static/index.js" charset="utf-8"></script>
<title>{{ .title }}</title>
</head>
<body>
    <p>{{ .oh }}</p
    <p>{{ .name }}</p>
</body>
</html>

Getting Started via Pongo template

package main

import (
	"github.com/insionng/makross"
	"github.com/insionng/makross/logger"
	"github.com/insionng/makross/pongor"
	"github.com/insionng/makross/recover"
	"github.com/insionng/makross/static"
)

func main() {
	v := makross.New()
	v.Use(logger.Logger())
	v.Use(recover.Recover())
	v.SetRenderer(pongor.Renderor())
	v.Use(static.Static("static"))
	v.Get("/", func(self *makross.Context) error {
		var data = make(map[string]interface{})
		data["name"] = "Insion Ng"
		self.SetStore(data)

		self.SetStore(map[string]interface{}{
			"title": "你好,世界",
			"oh":    "no",
		})
		self.Set("oh", "yes") //覆盖前面指定KEY
		return self.Render("index")
	})

	v.Listen(":9000")
}

templates/index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="/static/index.js" charset="utf-8"></script>
<title>{{ title }}</title>
</head>
<body>
    <p>{{ oh }}</p
    <p>{{ name }}</p>
</body>
</html>

Getting Started via FastTemplate

package main

import (
	"github.com/insionng/makross"
	"github.com/insionng/makross/fempla"
	"github.com/insionng/makross/logger"
	"github.com/insionng/makross/recover"
	"github.com/insionng/makross/static"
)

func main() {

	v := makross.New()
	v.Use(logger.Logger())
	v.Use(recover.Recover())
	v.SetRenderer(fempla.Renderor())
	v.Use(static.Static("static"))
	v.Get("/", func(self *makross.Context) error {
		data := make(map[string]interface{})
		data["oh"] = "no"
		data["name"] = "Insion Ng"
		self.Set("title", "你好,世界")
		self.SetStore(data)
		self.Set("oh", "yes")
		return self.Render("index")
	})

	v.Listen(":9000")

}

templates/index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="/static/index.js" charset="utf-8"></script>
<title>{{title}}</title>
</head>
<body>
    <p>
        {{oh}}
    </p>
    <p>
        {{name}}
    </p>
</body>
</html>

Case

Below we describe how to create a simple REST API using Makross.

Create a server.go file with the following content:

package main

import (
	"log"
	"net/http"
	"github.com/insionng/makross"
	"github.com/insionng/makross/access"
	"github.com/insionng/makross/slash"
	"github.com/insionng/makross/content"
	"github.com/insionng/makross/fault"
	"github.com/insionng/makross/file"
)

func main() {
	m := makross.New()

	m.Use(
		// all these handlers are shared by every route
		access.Logger(log.Printf),
		slash.RemoveTrailingSlash(),
		fault.Recovery(log.Printf),
	)

	// serve RESTful APIs
	api := m.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 *makross.Context) error {
		return c.Write("user list")
	})
	api.Post("/users", func(c *makross.Context) error {
		return c.Write("create a new user")
	})
	api.Put(`/users/<id:\d+>`, func(c *makross.Context) error {
		return c.Write("update user " + c.Param("id"))
	})

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

	m.Listen(8888)
}

Create an HTML file ui/index.html with any content.

Now run the following command to start the Web server:

go run server.go

You should be able to access URLs such as http://localhost:8888, http://localhost:8888/api/users.

Routes

Makross works by building a makross table in a router and then dispatching HTTP requests to the matching handlers found in the makross table. An intuitive illustration of a makross 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 makross table uses a variant of the radix tree data structure, which makes the makross 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 makross table, call the To method like the following:

m := makross.New()
m.To("GET", "/users", m1, m2, h1)
m.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:

m.Get("/users", m1, m2, h1)
m.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,

m.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:

m.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/<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():

m := makross.New()

m.Get("/users/<username>", func (c *makross.Context) error {
	fmt.Fprintf(c.Response, "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,

m := makross.New()
api := m.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 makross 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 makross 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,

m := makross.New()
m.Use(m1)

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

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

Because the makross 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 makross table and dispatches incoming requests to appropriate handlers. A router instance is created by calling the makross.New() method.

Because Router implements the http.Handler interface, it can be readily used to serve subtrees on existing Go servers. For example,

m := makross.New()
m.Listen(9999)
Handlers

A handler is a function with the signature func(*makross.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 makross.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 makross.Context object is populated with the request information and passed through the handlers that need to handle the request. Handlers can get the request information via Context.Request and send a response back via Context.Response. 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().

Reading Request Data

Context provides a few shortcut methods to read query parameters. The Context.Query() method returns the named URL query parameter value; the Context.PostForm() method returns the named parameter value in the POST or PUT body parameters; and the Context.Form() method returns the value from either POST/PUT or URL query parameters.

The Context.Read() method supports reading data from the request body and populating it into an object. The method will check the Content-Type HTTP header and parse the body data as the corresponding format. For example, if Content-Type is application/json, the request body will be parsed as JSON data. The public fields in the object being populated will receive the parsed data if the data contains the same named fields. For example,

func foo(c *makross.Context) error {
    data := &struct{
        A string
        B bool
    }{}

    // assume the body data is: {"A":"abc", "B":true}
    // data will be populated as: {A: "abc", B: true}
    if err := c.Read(&data); err != nil {
        return err
    }
}

By default, Context supports reading data that are in JSON, XML, form, and multipart-form data. You may modify makross.DataReaders to add support for other data formats.

Note that when the data is read as form data, you may use struct tag named form to customize the name of the corresponding field in the form data. The form data reader also supports populating data into embedded objects which are either named or anonymous.

Writing Response Data

The Context.Write() method can be used to write data of arbitrary type to the response. By default, if the data being written is neither a string nor a byte array, the method will will call fmt.Fprint() to write the data into the response.

You can call Context.SetWriter() to replace the default data writer with a customized one. For example, the content.TypeNegotiator will negotiate the content response type and set the data writer with an appropriate one.

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():

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

Serving Static Files

Static files can be served with the help of file.Server and file.Content handlers. The former serves files under the specified directories, while the latter serves the content of a single file. For example,

import (
	"github.com/insionng/makross"
	"github.com/insionng/makross/file"
)

m := makross.New()

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

Handlers

Makross comes with a few commonly used handlers in its subpackages:

Handler name Description
access.Logger records an entry for every incoming request
auth.Basic provides authentication via HTTP Basic
auth.Bearer provides authentication via HTTP Bearer
auth.Query provides authentication via token-based query parameter
auth.JWT provides JWT-based authentication
content.TypeNegotiator supports content negotiation by response types
content.LanguageNegotiator supports content negotiation by accepted languages
cors.Handler implements the CORS (Cross Origin Resource Sharing) specification from the W3C
fault.Recovery recovers from panics and handles errors returned by handlers
fault.PanicHandler recovers from panics happened in the handlers
fault.ErrorHandler handles errors returned by handlers by writing them in an appropriate format to the response
file.Server serves the files under the specified folder as response content
file.Content serves the content of the specified file as the response
slash.Remover removes the trailing slashes from the request URL and redirects to the proper URL

The following code shows how these handlers may be used:

import (
	"log"
	"net/http"
	"github.com/insionng/makross"
	"github.com/insionng/makross/access"
	"github.com/insionng/makross/slash"
	"github.com/insionng/makross/fault"
)

m := makross.New()

m.Use(
	access.Logger(log.Printf),
	slash.Remover(http.StatusMovedPermanently),
	fault.Recovery(log.Printf),
)

...
Third-party Handlers

The following third-party handlers are specifically designed for Makross:

Handler name Description
jwt.JWT supports JWT Authorization

Makross also provides adapters to support using third-party http.HandlerFunc or http.Handler handlers. For example,

m := makross.New()

// using http.HandlerFunc
m.Use(makross.HTTPHandlerFunc(http.NotFound))

// using http.Handler
m.Use(makross.HTTPHandler(http.NotFoundHandler))
Contributes

Thanks to the macross, com, echo/vodka, iris, gin, beego, ozzo-routing, FastTemplate, Pongo2, Jwt-go. And all other Go package dependencies projects

Recipes
  • Zenpress Zenpres,the cms project like wordpress

Documentation

Index

Constants

View Source
const (
	CONNECT = "CONNECT"
	DELETE  = "DELETE"
	GET     = "GET"
	HEAD    = "HEAD"
	OPTIONS = "OPTIONS"
	PATCH   = "PATCH"
	POST    = "POST"
	PUT     = "PUT"
	TRACE   = "TRACE"
)

Export HTTP methods

View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; " + charsetUTF8
	MIMETextXML                          = "text/xml"
	MIMETextXMLCharsetUTF8               = MIMETextXML + "; " + charsetUTF8
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf              = "application/protobuf"
	MIMEApplicationMsgpack               = "application/msgpack"
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm                    = "multipart/form-data"
	MIMEOctetStream                      = "application/octet-stream"
)

MIME types

View Source
const (
	HeaderAccept              = "Accept"
	HeaderAcceptEncoding      = "Accept-Encoding"
	HeaderAllow               = "Allow"
	HeaderAuthorization       = "Authorization"
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderCookie              = "Cookie"
	HeaderSetCookie           = "Set-Cookie"
	HeaderIfModifiedSince     = "If-Modified-Since"
	HeaderLastModified        = "Last-Modified"
	HeaderLocation            = "Location"
	HeaderUpgrade             = "Upgrade"
	HeaderVary                = "Vary"
	HeaderWWWAuthenticate     = "WWW-Authenticate"
	HeaderXForwardedFor       = "X-Forwarded-For"
	HeaderXForwardedProto     = "X-Forwarded-Proto"
	HeaderXForwardedProtocol  = "X-Forwarded-Protocol"
	HeaderXForwardedSsl       = "X-Forwarded-Ssl"
	HeaderXUrlScheme          = "X-Url-Scheme"
	HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
	HeaderXRealIP             = "X-Real-IP"
	HeaderXRequestID          = "X-Request-ID"
	HeaderServer              = "Server"
	HeaderOrigin              = "Origin"

	// Access control
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	// Security
	HeaderStrictTransportSecurity = "Strict-Transport-Security"
	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderXXSSProtection          = "X-XSS-Protection"
	HeaderXFrameOptions           = "X-Frame-Options"
	HeaderContentSecurityPolicy   = "Content-Security-Policy"
	HeaderXCSRFToken              = "X-CSRF-Token"
)

Headers

View Source
const (
	StatusContinue           = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1

	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusPartialContent       = 206 // RFC 7233, 4.1
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently = 301 // RFC 7231, 6.4.2
	StatusFound            = 302 // RFC 7231, 6.4.3
	StatusSeeOther         = 303 // RFC 7231, 6.4.4
	StatusNotModified      = 304 // RFC 7232, 4.1
	StatusUseProxy         = 305 // RFC 7231, 6.4.5

	StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect = 308 // RFC 7538, 3

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

Status HTTP status codes as registered with IANA. See: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

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.

View Source
const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"

TimeFormat is the time format to use when generating times in HTTP headers. It is like time.RFC1123 but hard-codes GMT as the time zone. The time being formatted must be in UTC for Format to generate the correct format.

For parsing this time format, see ParseTime.

Variables

View Source
var (
	ErrUnsupportedMediaType        = NewHTTPError(StatusUnsupportedMediaType)
	ErrNotFound                    = NewHTTPError(StatusNotFound)
	ErrStatusBadRequest            = NewHTTPError(StatusBadRequest)
	ErrUnauthorized                = NewHTTPError(StatusUnauthorized)
	ErrForbidden                   = NewHTTPError(http.StatusForbidden)
	ErrMethodNotAllowed            = NewHTTPError(StatusMethodNotAllowed)
	ErrStatusRequestEntityTooLarge = NewHTTPError(StatusRequestEntityTooLarge)
	ErrRendererNotRegistered       = errors.New("renderer not registered")
	ErrInvalidRedirectCode         = errors.New("invalid redirect status code")
	ErrCookieNotFound              = errors.New("cookie not found")
)

Errors

View Source
var (
	// Methods lists all supported HTTP methods by Makross.
	Methods = []string{
		CONNECT,
		DELETE,
		GET,
		HEAD,
		OPTIONS,
		PATCH,
		POST,
		PUT,
		TRACE,
	}

	// FlashNow applies to current request.
	FlashNow bool
)
View Source
var (
	// DefaultPriority 默认优先级为0值
	DefaultPriority int
)

Functions

func Config

func Config() *ini.File

Config returns configuration convention object. It returns an empty object if there is no one available.

func GetAddress

func GetAddress(args ...interface{}) string

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.

func SetConfig

func SetConfig(source interface{}, others ...interface{}) (_ *ini.File, err error)

SetConfig sets data sources for configuration.

func StatusText

func StatusText(code int) string

StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.

Types

type Args

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

func (*Args) Bytes

func (a *Args) Bytes() []byte

func (*Args) Exist

func (a *Args) Exist() bool

func (*Args) Float32

func (a *Args) Float32() (f float32, e error)

func (*Args) Float64

func (a *Args) Float64() (f float64, e error)

func (*Args) Int

func (a *Args) Int() (int, error)

func (*Args) Int64

func (a *Args) Int64() (int64, error)

func (*Args) MustFloat32

func (a *Args) MustFloat32() (f float32)

func (*Args) MustFloat64

func (a *Args) MustFloat64() (f float64)

func (*Args) MustInt

func (a *Args) MustInt() int

func (*Args) MustInt64

func (a *Args) MustInt64() int64

func (*Args) MustUint

func (a *Args) MustUint() uint

func (*Args) MustUint8

func (a *Args) MustUint8() uint8

func (*Args) String

func (a *Args) String() string

func (*Args) Time

func (a *Args) Time() time.Time

func (*Args) ToSnakeCase

func (a *Args) ToSnakeCase(str ...string) string

func (*Args) ToStr

func (a *Args) ToStr(args ...int) (s string)

type BindUnmarshaler

type BindUnmarshaler interface {
	// UnmarshalParam decodes and assigns a value from an form or query param.
	UnmarshalParam(param string) error
}

BindUnmarshaler is the interface used to wrap the UnmarshalParam method.

type Binder

type Binder interface {
	Bind(i interface{}, c *Context) error
}

Binder is the interface that wraps the Bind method.

type Context

type Context struct {
	Request  *http.Request // the current request
	Response *Response     // the response writer

	Localer
	Flash   *Flash
	Session Sessioner

	FiltersMap *sync.Map //map[string][]byte      // Not Global Filters, only in Context
	// contains filtered or unexported fields
}

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

func (*Context) Abort

func (c *Context) Abort() error

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

func (c *Context) AddActionHook(key string, function func(), priorities ...int)

AddActionHook (c *Context) 增加动作钩子

func (*Context) AddFilterHook

func (c *Context) AddFilterHook(key string, function func([]byte) []byte, priorities ...int)

AddFilterHook (c *Context) 增加过滤钩子

func (*Context) Args

func (c *Context) Args(key ...string) *Args

Args 先从URL获取参数,如若没有则再尝试从from获取参数

func (*Context) Attachment

func (c *Context) Attachment(file, name string) (err error)

func (*Context) Bind

func (c *Context) Bind(i interface{}) error

func (*Context) Blob

func (c *Context) Blob(contentType string, b []byte, status ...int) (err error)

func (*Context) Break

func (c *Context) Break(status int, err ...error) error

Break 中断继续执行后续动作,返回指定状态及错误,不设置错误亦可.

func (*Context) Close

func (c *Context) Close() error

Close 立即关闭HTTP服务

func (*Context) ContentTypeByExtension

func (c *Context) ContentTypeByExtension(name string) (t string)

ContentTypeByExtension returns the MIME type associated with the file based on its extension. It returns `application/octet-stream` incase MIME type is not found.

func (*Context) DoActionHook

func (c *Context) DoActionHook(key string, globals ...bool)

DoActionHook (c *Context) 动作钩子

func (*Context) DoFilterHook

func (c *Context) DoFilterHook(key string, function func() []byte, globals ...bool) []byte

DoFilterHook (c *Context) 执行过滤钩子

func (*Context) Error

func (c *Context) Error(status int, message ...interface{})

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

func (c *Context) FormArgs(key ...string) *Args

func (*Context) FormFile

func (c *Context) FormFile(name string) (*multipart.FileHeader, error)

func (*Context) FormParams

func (c *Context) FormParams() (url.Values, error)

func (*Context) FormValue

func (c *Context) FormValue(name string) 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) GetCookie

func (c *Context) GetCookie(name string) (*http.Cookie, error)

func (*Context) GetCookies

func (c *Context) GetCookies() []*http.Cookie

func (*Context) GetStore

func (c *Context) GetStore() map[string]interface{}

func (*Context) HandleError

func (c *Context) HandleError(err error)

func (*Context) Handler

func (c *Context) Handler() Handler

func (*Context) HasActionHook

func (c *Context) HasActionHook(key string) bool

HasActionHook (c *Context) 是否有动作钩子

func (*Context) HasFilterHook

func (c *Context) HasFilterHook(key string, globals ...bool) bool

HasFilterHook (c *Context) 是否有过滤钩子

func (*Context) HasQueuesMap

func (c *Context) HasQueuesMap(key string) bool

HasQueuesMap (c *Context) Has QueuesMap

func (*Context) Inline

func (c *Context) Inline(file, name string) (err error)

func (*Context) IsTLS

func (c *Context) IsTLS() bool

IsTLS implements `Context#TLS` function.

func (*Context) IsWebSocket

func (c *Context) IsWebSocket() bool

func (*Context) JSON

func (c *Context) JSON(i interface{}, status ...int) (err error)

func (*Context) JSONBlob

func (c *Context) JSONBlob(b []byte, status ...int) (err error)

func (*Context) JSONP

func (c *Context) JSONP(callback string, i interface{}, status ...int) (err error)

func (*Context) JSONPBlob

func (c *Context) JSONPBlob(callback string, b []byte, status ...int) (err error)

func (*Context) JSONPretty

func (c *Context) JSONPretty(i interface{}, indent string, status ...int) (err error)

func (*Context) Kontext

func (c *Context) Kontext() ktx.Context

func (*Context) Makross

func (c *Context) Makross() *Makross

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

func (*Context) MultipartForm

func (c *Context) MultipartForm() (*multipart.Form, error)

func (*Context) NewCookie

func (c *Context) NewCookie() *http.Cookie

func (*Context) NewHTTPError

func (c *Context) NewHTTPError(status int, message ...interface{}) *HTTPError

NewHTTPError creates a new HTTPError instance.

func (*Context) NewNode

func (c *Context) NewNode(key interface{}, v interface{}, priority int) *prior.Node

func (*Context) NewPriorityQueue

func (c *Context) NewPriorityQueue() *prior.PriorityQueue

NewPriorityQueue New PriorityQueue

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

func (c *Context) NoContent(status ...int) error

NoContent Only header

func (*Context) Param

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

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

func (c *Context) Parameter(i int) (value string)

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

func (c *Context) Pull(key string) interface{}

func (*Context) PullStore

func (c *Context) PullStore() map[string]interface{}

func (*Context) Push

func (c *Context) Push(key string, value interface{})

func (*Context) PushStore

func (c *Context) PushStore(data map[string]interface{})

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

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

func (*Context) QueryParams

func (c *Context) QueryParams() url.Values

func (*Context) QueryString

func (c *Context) QueryString() 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) RealIP

func (c *Context) RealIP() string

RealIP implements `Context#RealIP` function.

func (*Context) Redirect

func (c *Context) Redirect(url string, status ...int) error

func (*Context) RemoveActionHook

func (c *Context) RemoveActionHook(key string, globals ...bool)

RemoveActionHook (c *Context) 删除动作钩子

func (*Context) RemoveActionsHook

func (c *Context) RemoveActionsHook()

RemoveActionsHook (c *Context) 删除所有动作钩子

func (*Context) RemoveFilterHook

func (c *Context) RemoveFilterHook(key string, globals ...bool)

RemoveFilterHook (c *Context) 删除过滤钩子

func (*Context) Render

func (c *Context) Render(name string, status ...int) (err error)

func (*Context) RequestBody

func (c *Context) RequestBody() io.Reader

func (*Context) RequestHeader

func (c *Context) RequestHeader(key string) string

RequestHeader returns the request header's value accepts one parameter, the key of the header (string) returns string

func (*Context) RequestURI

func (c *Context) RequestURI() string

func (*Context) Reset

func (c *Context) Reset(w http.ResponseWriter, r *http.Request)

Reset sets the request and response of the context and resets all other properties.

func (*Context) Scheme

func (c *Context) Scheme() string

func (*Context) SendFile

func (c *Context) SendFile(filename string, destinationName string) error

SendFile sends file for force-download to the client

Use this instead of ServeFile to 'force-download' bigger files to the client

func (*Context) ServeContent

func (c *Context) ServeContent(content io.ReadSeeker, filename string, modtime time.Time) error

ServeContent serves content, headers are autoset receives three parameters, it's low-level function, instead you can use .ServeFile(string,bool)/SendFile(string,string)

You can define your own "Content-Type" header also, after this function call Doesn't implements resuming (by range), use ctx.SendFile instead

func (*Context) ServeFile

func (c *Context) ServeFile(file string) (err error)

ServeFile serves a view file, to send a file ( zip for example) to the client you should use the SendFile(serverfilename,clientfilename)

You can define your own "Content-Type" header also, after this function call This function doesn't implement resuming (by range), use ctx.SendFile/fasthttp.ServeFileUncompressed(ctx.RequestCtx,path)/fasthttpServeFile(ctx.RequestCtx,path) instead

Use it when you want to serve css/js/... files to the client, for bigger files and 'force-download' use the SendFile

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

func (c *Context) SetCookie(cookie *http.Cookie)

func (*Context) SetDataWriter

func (c *Context) SetDataWriter(writer DataWriter)

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

func (*Context) SetHandler

func (c *Context) SetHandler(h Handler)

func (*Context) SetKontext

func (c *Context) SetKontext(ktx ktx.Context)

func (*Context) SetPriorityQueueWith

func (c *Context) SetPriorityQueueWith(key interface{}) *sync.Map

SetPriorityQueueWith c.makross.QueuesMap[key] = c.NewPriorityQueue()

func (*Context) SetStore

func (c *Context) SetStore(data map[string]interface{})

func (*Context) Shutdown

func (c *Context) Shutdown(times ...int64) error

Shutdown 优雅停止HTTP服务 不超过特定时长

func (*Context) Stream

func (c *Context) Stream(contentType string, r io.Reader, status ...int) (err error)

func (*Context) String

func (c *Context) String(s string, status ...int) (err error)

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

func (c *Context) UserAgent() string

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.

func (*Context) XML

func (c *Context) XML(i interface{}, status ...int) (err error)

func (*Context) XMLBlob

func (c *Context) XMLBlob(b []byte, status ...int) (err error)

func (*Context) XMLPretty

func (c *Context) XMLPretty(i interface{}, indent string, status ...int) (err error)

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 DefaultBinder

type DefaultBinder struct{}

DefaultBinder is the default implementation of the Binder interface.

func (*DefaultBinder) Bind

func (b *DefaultBinder) Bind(i interface{}, c *Context) (err error)

Bind implements the `Binder#Bind` function.

type Flash

type Flash struct {
	FlashNow bool
	Ctx      *Context
	url.Values
	ErrorMsg, WarningMsg, InfoMsg, SuccessMsg string
}

func (*Flash) Error

func (f *Flash) Error(msg string, current ...bool)

func (*Flash) Info

func (f *Flash) Info(msg string, current ...bool)

func (*Flash) Success

func (f *Flash) Success(msg string, current ...bool)

func (*Flash) Warning

func (f *Flash) Warning(msg string, current ...bool)

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 struct {
	Status  int    //`json:"status" xml:"status"`
	Message string //`json:"message" xml:"message"`
}

Error contains the error information reported by calling Context.Error(). HTTPError represents an error that occurred while handling a request.

func NewHTTPError

func NewHTTPError(status int, message ...interface{}) *HTTPError

NewHTTPError creates a new HTTPError instance.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error returns the error message.

func (*HTTPError) StatusCode

func (e *HTTPError) StatusCode() int

StatusCode returns the HTTP 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 makross.Handler.

func HTTPHandlerFunc

func HTTPHandlerFunc(h http.HandlerFunc) Handler

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

func WrapHTTPHandler

func WrapHTTPHandler(handler http.Handler) Handler

WrapHTTPHandler wraps `http.Handler` into `makross.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 Localer

type Localer interface {
	Language() string
	Tr(string, ...interface{}) string
}

Localer reprents a localization interface.

type Makross

type Makross struct {
	RouteGroup

	QueuesMap  *sync.Map //map[string]*prior.PriorityQueue
	FiltersMap *sync.Map //map[string][]byte // Global Filters

	Server *http.Server
	// contains filtered or unexported fields
}

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

func New

func New() (m *Makross)

New creates a new Makross object.

func (*Makross) AcquireContext

func (m *Makross) AcquireContext() *Context

AcquireContext returns an empty `Context` instance from the pool. You must return the context by calling `ReleaseContext()`.

func (*Makross) AddActionHook

func (m *Makross) AddActionHook(key string, function func(), priorities ...int)

AddActionHook (m *Makross) 增加动作钩子

func (*Makross) AddFilterHook

func (m *Makross) AddFilterHook(key string, function func([]byte) []byte, priorities ...int)

AddFilterHook (m *Makross) 增加过滤钩子

func (*Makross) Binder

func (m *Makross) Binder() Binder

Binder returns the binder instance.

func (*Makross) Close

func (m *Makross) Close() error

Close 立即关闭HTTP服务

func (*Makross) DoActionHook

func (m *Makross) DoActionHook(key string)

DoActionHook (m *Makross) 动作钩子

func (*Makross) DoFilterHook

func (m *Makross) DoFilterHook(key string, function func() []byte) []byte

DoFilterHook (m *Makross) 执行过滤钩子

func (*Makross) File

func (m *Makross) File(path, file string)

File registers a new route with path to serve a static file.

func (*Makross) HandleError

func (m *Makross) HandleError(c *Context, err interface{})

HandleError is the error handler for handling any unhandled errors.

func (*Makross) HasActionHook

func (m *Makross) HasActionHook(key string) bool

HasActionHook (m *Makross) 是否有动作钩子

func (*Makross) HasFilterHook

func (m *Makross) HasFilterHook(key string) bool

HasFilterHook (m *Makross) 是否有过滤钩子

func (*Makross) HasQueuesMap

func (m *Makross) HasQueuesMap(key string) bool

HasQueuesMap (m *Makross) Has QueuesMap

func (*Makross) Listen

func (m *Makross) Listen(args ...interface{})

func (*Makross) ListenTLS

func (m *Makross) ListenTLS(certFile, keyFile string, args ...interface{})

func (*Makross) NewContext

func (m *Makross) NewContext(r *http.Request, w http.ResponseWriter, handlers ...Handler) *Context

NewContext returns a Context instance.

func (*Makross) NewHTTPError

func (m *Makross) NewHTTPError(status int, message ...interface{}) *HTTPError

NewHTTPError creates a new HTTPError instance.

func (*Makross) NewNode

func (m *Makross) NewNode(key interface{}, v interface{}, priority int) *prior.Node

func (*Makross) NewPriorityQueue

func (m *Makross) NewPriorityQueue() *prior.PriorityQueue

NewPriorityQueue New PriorityQueue

func (*Makross) NotFound

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

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

func (*Makross) Pull

func (m *Makross) Pull(key string) interface{}

func (*Makross) PullStore

func (m *Makross) PullStore() map[string]interface{}

func (*Makross) Push

func (m *Makross) Push(key string, value interface{})

func (*Makross) PushStore

func (m *Makross) PushStore(data map[string]interface{})

func (*Makross) ReleaseContext

func (m *Makross) ReleaseContext(c *Context)

ReleaseContext returns the `Context` instance back to the pool. You must call it after `AcquireContext()`.

func (*Makross) RemoveActionHook

func (m *Makross) RemoveActionHook(key string)

RemoveActionHook (m *Makross) 删除动作钩子

func (*Makross) RemoveActionsHook

func (m *Makross) RemoveActionsHook()

RemoveActionsHook (m *Makross) 删除所有动作钩子

func (*Makross) RemoveFilterHook

func (m *Makross) RemoveFilterHook(key string)

RemoveFilterHook (m *Makross) 删除过滤钩子

func (*Makross) Route

func (m *Makross) Route(name string) *Route

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

func (*Makross) Routes

func (m *Makross) Routes() []*Route

Routes returns all routes managed by the makross.

func (*Makross) ServeHTTP

func (m *Makross) ServeHTTP(res http.ResponseWriter, req *http.Request)

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

func (*Makross) SetBinder

func (m *Makross) SetBinder(b Binder)

SetBinder registers a custom binder. It's invoked by `Context#Bind()`.

func (*Makross) SetPriorityQueueWith

func (m *Makross) SetPriorityQueueWith(key interface{}) *sync.Map

SetPriorityQueueWith c.makross.QueuesMap[key] = c.NewPriorityQueue()

func (*Makross) SetRenderer

func (m *Makross) SetRenderer(r Renderer)

SetRenderer registers an HTML template renderer. It's invoked by `Context#Render()`.

func (*Makross) Shutdown

func (m *Makross) Shutdown(times ...int64) error

Shutdown 优雅停止HTTP服务 不超过特定时长

func (*Makross) Static

func (m *Makross) Static(prefix, root string)

Static registers a new route with path prefix to serve static files from the provided root directory.

func (*Makross) Use

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

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

type RawStore

type RawStore interface {
	// Set sets value to given key in session.
	Set(interface{}, interface{}) error
	// Get gets value by given key in session.
	Get(interface{}) interface{}
	// Delete deletes a key from session.
	Delete(interface{}) error
	// ID returns current session ID.
	ID() string
	// Release releases session resource and save data to provider.
	Release(*Context) error
	// Flush deletes all session data.
	Flush() error
}

RawStore is the interface that operates the session data.

type Renderer

type Renderer interface {
	Render(io.Writer, string, *Context) error
}

Renderer is the interface that wraps the Render function.

type Response

type Response struct {
	Writer    http.ResponseWriter
	Status    int
	Size      int64
	Committed bool
	// contains filtered or unexported fields
}

Response wraps an http.ResponseWriter and implements its interface to be used by an HTTP handler to construct an HTTP response. See: https://golang.org/pkg/net/http/#ResponseWriter

func NewResponse

func NewResponse(w http.ResponseWriter, m *Makross) (r *Response)

NewResponse creates a new instance of Response.

func (*Response) CloseNotify

func (r *Response) CloseNotify() <-chan bool

CloseNotify implements the http.CloseNotifier interface to allow detecting when the underlying connection has gone away. This mechanism can be used to cancel long operations on the server if the client has disconnected before the response is ready. See http.CloseNotifier(https://golang.org/pkg/net/http/#CloseNotifier)

func (*Response) Flush

func (r *Response) Flush()

Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client. See http.Flusher(https://golang.org/pkg/net/http/#Flusher)

func (*Response) Header

func (r *Response) Header() http.Header

Header returns the header map for the writer that will be sent by WriteHeader. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example) To suppress implicit response headers, set their value to nil. Example: https://golang.org/pkg/net/http/#example_ResponseWriter_trailers

func (*Response) Hijack

func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection. See http.Hijacker(https://golang.org/pkg/net/http/#Hijacker)

func (*Response) Write

func (r *Response) Write(b []byte) (n int, err error)

Write writes the data to the connection as part of an HTTP reply.

func (*Response) WriteHeader

func (r *Response) WriteHeader(code int)

WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.

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 makross using the CONNECT HTTP method.

func (*Route) Delete

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

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

func (*Route) Get

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

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

func (*Route) Head

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

Head adds the route to the makross 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 makross as well.

func (*Route) Options

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

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

func (*Route) Patch

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

Patch adds the route to the makross 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 makross using the POST HTTP method.

func (*Route) Put

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

Put adds the route to the makross 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 makross 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 makross 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 makross.Methods.

func (*RouteGroup) Connect

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

Connect adds a CONNECT route to the makross 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 makross with the given route path and handlers.

func (*RouteGroup) Get

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

Get adds a GET route to the makross 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 makross 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 makross 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 makross 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 makross 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 makross with the given route path and handlers.

func (*RouteGroup) SetRenderer

func (rg *RouteGroup) SetRenderer(r Renderer)

SetRenderer registers an HTML template renderer.

func (*RouteGroup) To

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

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

func (*RouteGroup) Trace

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

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

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 Sessioner

type Sessioner interface {
	RawStore
	//---------------------------------------------//
	// Read returns raw session store by session ID.
	Read(string) (RawStore, error)
	// Destory deletes a session.
	Destory(*Context) error
	// RegenerateId regenerates a session store from old session ID to new one.
	RegenerateId(*Context) (RawStore, error)
	// Count counts and returns number of sessions.
	Count() int
	// GC calls GC to clean expired sessions.
	GC()
}

Sessioner is the interface that contains all data for one session process with specific ID.

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
Package access provides an access logging handler for the ozzo makross package.
Package access provides an access logging handler for the ozzo makross package.
Package auth provides a set of user authentication handlers for the makross.
Package auth provides a set of user authentication handlers for the makross.
Package captcha a middleware that provides captcha service for Macross.
Package captcha a middleware that provides captcha service for Macross.
Package content provides content negotiation handlers for the makross.
Package content provides content negotiation handlers for the makross.
Package cors provides a handler for handling CORS.
Package cors provides a handler for handling CORS.
Package fault provides a panic and error handler for the makross.
Package fault provides a panic and error handler for the makross.
Package file provides handlers that serve static files for the ozzo makross package.
Package file provides handlers that serve static files for the ozzo makross package.
Package i18n is a middleware that provides app Internationalization and Localization of Macross.
Package i18n is a middleware that provides app Internationalization and Localization of Macross.
jwt
libraries
com
Package com is an open source project for commonly used functions for the Go programming language.
Package com is an open source project for commonly used functions for the Go programming language.
femplate
Package femplate implements simple and fast template library.
Package femplate implements simple and fast template library.
i18n
Package i18n is for app Internationalization and Localization.
Package i18n is for app Internationalization and Localization.
i18n/ui18n
ui18n is a helper tool for Unknwon/i18n package.
ui18n is a helper tool for Unknwon/i18n package.
ini.v1
Package ini provides INI file read and write functionality in Go.
Package ini provides INI file read and write functionality in Go.

Jump to

Keyboard shortcuts

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