macross

package module
v0.0.0-...-4cbec95 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2017 License: MIT Imports: 30 Imported by: 18

README

Macross

The Macross Web Framework By Insion

If you are using standard http, you may use a similar macross package makross which is adapted from Macross.

Requirements

Go 1.7.4 or above.

Installation

Run the following command to install the package:

go get -u github.com/insionng/macross

Getting Started

Create a server.go file with the following content:

package main

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

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

	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/macross"
	"github.com/insionng/macross/cors"
	"github.com/insionng/macross/jwt"
	"github.com/insionng/macross/logger"
	"github.com/insionng/macross/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: Macross
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 := macross.New()
	m.Use(logger.Logger())
	m.Use(recover.Recover())
	m.Use(cors.CORS())

	m.Get("/", func(self *macross.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 *macross.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(macross.HTTPError)
		herr.Message = "ErrUnauthorized"
		herr.Status = macross.StatusUnauthorized
		return self.JSON(herr, macross.StatusUnauthorized)

	})

	g := m.Group("/jwt", jwt.JWT(secret))
	// http://localhost:9000/jwt/get/
	g.Get("/get/", func(self *macross.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(macross.HeaderAccessControlExposeHeaders, "Authorization")
			self.Response.Header.Set("Authorization", jwt.Bearer+" "+tokenString)
			self.Set(jwt.DefaultJWTConfig.ContextKey, token)
		}

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

	m.Listen(":9000")
}

Getting Started via Session

package main

import (
	"github.com/insionng/macross"
	"github.com/insionng/macross/recover"
	"github.com/macross-contrib/session"
	_ "github.com/macross-contrib/session/redis"
	"log"
)

func main() {

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

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

		return self.String(value)

	})

	v.Get("/set", func(self *macross.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/macross"
	"github.com/macross-contrib/i18n"
)

func main() {
	m := macross.Classic()
	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 *macross.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 *macross.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/macross"
	"github.com/insionng/macross/gonder"
	"github.com/insionng/macross/logger"
	"github.com/insionng/macross/recover"
	"github.com/insionng/macross/static"
)

func main() {
	v := macross.New()
	v.Use(logger.Logger())
	v.Use(recover.Recover())
	v.SetRenderer(gonder.Renderor())
	v.Use(static.Static("static"))
	v.Get("/", func(self *macross.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/macross"
	"github.com/insionng/macross/logger"
	"github.com/insionng/macross/pongor"
	"github.com/insionng/macross/recover"
	"github.com/insionng/macross/static"
)

func main() {
	v := macross.New()
	v.Use(logger.Logger())
	v.Use(recover.Recover())
	v.SetRenderer(pongor.Renderor())
	v.Use(static.Static("static"))
	v.Get("/", func(self *macross.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/macross"
	"github.com/insionng/macross/fempla"
	"github.com/insionng/macross/logger"
	"github.com/insionng/macross/recover"
	"github.com/insionng/macross/static"
)

func main() {

	v := macross.New()
	v.Use(logger.Logger())
	v.Use(recover.Recover())
	v.SetRenderer(fempla.Renderor())
	v.Use(static.Static("static"))
	v.Get("/", func(self *macross.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>

Routes

macross works by building a macross table in a macross and then dispatching HTTP requests to the matching handlers found in the macross table. An intuitive illustration of a macross 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 macross table uses a variant of the radix tree data structure, which makes the macross process as fast as working with a hash table.

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

m := macross.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/root
  • /users/accnt-<id:\d+>: matches /users/accnt-123, but not /users/accnt-root
  • /users/<username>/*: matches /users/root/profile/address

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

m := macross.New()

m.Get("/users/<username>", func (self *macross.Context) error {
	username := self.Param("username").String()
	s := fmt.Sprintf("Name: %s", username)
	return self.String(s)
})
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 := macross.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 macross 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 macross 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 macross serves as the top level route group. A child group inherits the handlers registered with its parent group. For example,

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

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

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

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

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

m := macross.New()
m.Listen(":9000") 
Handlers

A handler is a function with the signature func(*macross.Context) error. A handler is executed by the macross if the incoming request URL path matches the route that the handler is associated with. Through the macross.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 macross will skip the rest of the handlers and handle the returned error.
  • A handler calls Context.Abort() and Context.Break(): the macross 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 macross.Context object is passed through the relevant handlers. Because macross.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() , Context.GetStore() and Context.Set() , Context.SetStore(), 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 Data() method that can be used to write data of arbitrary type to the response. The Data() 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 macross 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 macross 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():

  • macross.MethodNotAllowedHandler: a handler that sends an Allow HTTP header indicating the allowed HTTP methods for a requested URL
  • macross.NotFoundHandler: a handler triggering 404 HTTP error
Middleware
  • Cache: Middleware cache provides cache management for Macross. It can use many cache adapters, including memory, file, Redis.
  • Session: The session package is a Macross session manager. It can use many session providers.
  • I18n: Middleware i18n provides app Internationalization and Localization for Macross.
  • Macrus: Package macrus provides a middleware for macross that logs request details via the logrus logging library.
  • Statio: serves static files and http file system.
  • Captcha: Middleware captcha provides captcha service for Macross).
  • Macrof: A wrapper for macross to use net/http/pprof easily.
Contributes

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

Recipes
  • Yougam the discuss system project
  • Vuejsto the vue.js + macross example project
  • Drupapp the drupal models + macross project

Documentation

Overview

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

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

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
	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 (
	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"
	HeaderXForwardedProto               = "X-Forwarded-Proto"
	HeaderXHTTPMethodOverride           = "X-HTTP-Method-Override"
	HeaderXForwardedFor                 = "X-Forwarded-For"
	HeaderXRealIP                       = "X-Real-IP"
	HeaderServer                        = "Server"
	HeaderOrigin                        = "Origin"
	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 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)
	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 (

	// Flash applies to current request.
	FlashNow bool
)

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 Serialize

func Serialize(data interface{}) (bytes []byte, err error)

Serialize converts the given data into a byte array. If the data is neither a byte array nor a string, it will call fmt.Sprint to convert it into a string.

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 Binder

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

Binder is the interface that wraps the Bind method.

type Context

type Context struct {
	*fasthttp.RequestCtx

	Serialize SerializeFunc // the function serializing the given data of arbitrary type into a byte array.
	Session   Sessioner
	Localer
	Flash *Flash
	// 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) 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) Body

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

Body implements `Context#Body` function.

func (*Context) Break

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

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

func (*Context) ContentLength

func (c *Context) ContentLength() int64

ContentLength implements `Context#ContentLength` function.

func (*Context) ContentTypeByExtension

func (ctx *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) Cookie

func (ctx *Context) Cookie(name string) (*Cookie, error)

Cookie implements `Context#Cookie` function.

func (*Context) Cookies

func (ctx *Context) Cookies() []*Cookie

Cookies implements `Context#Cookies` function.

func (*Context) Data

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

Data writes the given data of arbitrary type to the response. The method calls the Serialize() method to convert the data into a byte array and then writes the byte array to the response.

func (*Context) Form

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

func (*Context) FormFile

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

FormFile implements `Context#FormFile` function.

func (*Context) FormParams

func (c *Context) FormParams() (params map[string][]string)

FormParams implements `Context#FormParams` function.

func (*Context) FormValue

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

FormValue implements `Context#FormValue` function.

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

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

func (*Context) GetURI

func (c *Context) GetURI() string

URI implements `Context#URI` function.

func (*Context) HTML

func (c *Context) HTML(html string, status ...int) (err error)

func (*Context) Handler

func (c *Context) Handler() Handler

func (*Context) Host

func (c *Context) Host() string

Host implements `Context#Host` function.

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

func (c *Context) Macross() *Macross

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

func (*Context) Method

func (c *Context) Method() string

Method implements `Context#Method` function.

func (*Context) MultipartForm

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

MultipartForm implements `Context#MultipartForm` function.

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

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

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

QueryParam implements `Context#QueryParam` function.

func (*Context) QueryParams

func (c *Context) QueryParams() (params map[string][]string)

QueryParams implements `Context#QueryParams` function.

func (*Context) QueryString

func (c *Context) QueryString() string

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

func (c *Context) Referer() string

Referer implements `Context#Referer` function.

func (*Context) RemoteAddress

func (c *Context) RemoteAddress() string

RemoteAddress implements `Context#RemoteAddress` function.

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 (ctx *Context) RequestHeader(k string) string

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

func (*Context) Reset

func (c *Context) Reset(ctx *fasthttp.RequestCtx)

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

func (*Context) Scheme

func (c *Context) Scheme() string

Scheme implements `Context#Scheme` function.

func (*Context) SendFile

func (ctx *Context) SendFile(filename string, destinationName string)

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 (ctx *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 (ctx *Context) ServeFile(file string) 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) SetBody

func (c *Context) SetBody(reader io.Reader)

SetBody implements `Context#SetBody` function.

func (*Context) SetCookie

func (ctx *Context) SetCookie(c *Cookie)

SetCookie implements `Context#SetCookie` function.

func (*Context) SetHandler

func (c *Context) SetHandler(h Handler)

func (*Context) SetHost

func (c *Context) SetHost(host string)

SetHost implements `Context#SetHost` function.

func (*Context) SetKontext

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

func (*Context) SetMethod

func (c *Context) SetMethod(method string)

SetMethod implements `Context#SetMethod` function.

func (*Context) SetStore

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

func (*Context) SetURI

func (c *Context) SetURI(uri string)

SetURI implements `Context#SetURI` function.

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

UserAgent implements `Context#UserAgent` function.

func (*Context) WrapAfterHandler

func (c *Context) WrapAfterHandler(handler Handler) Handler

func (*Context) WrapBeforeHandler

func (c *Context) WrapBeforeHandler(handler Handler) Handler

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 Cookie struct {
	fasthttp.Cookie
}

Cookie implements `Cookie`.

func (*Cookie) Domain

func (c *Cookie) Domain() string

Domain returns the cookie domain.

func (*Cookie) Expire

func (c *Cookie) Expire() time.Time

Expires returns the cookie expiry time.

func (*Cookie) HTTPOnly

func (c *Cookie) HTTPOnly() bool

HTTPOnly indicates if cookie is HTTPOnly.

func (*Cookie) Name

func (c *Cookie) Name() string

Name returns the cookie name.

func (*Cookie) Path

func (c *Cookie) Path() string

Path returns the cookie path.

func (*Cookie) Secure

func (c *Cookie) Secure() bool

Secure indicates if cookie is Secure.

func (*Cookie) SetDomain

func (c *Cookie) SetDomain(domain string)

SetDomain sets the cookie domain.

func (*Cookie) SetExpire

func (c *Cookie) SetExpire(expire time.Time)

SetExpire sets the cookie expiry time.

func (*Cookie) SetHTTPOnly

func (c *Cookie) SetHTTPOnly(httpOnly bool)

SetHTTPOnly sets the cookie as HTTPOnly.

func (*Cookie) SetName

func (c *Cookie) SetName(name string)

SetName sets cookie name.

func (*Cookie) SetPath

func (c *Cookie) SetPath(path string)

SetPath sets the cookie path.

func (*Cookie) SetSecure

func (c *Cookie) SetSecure(secure bool)

SetSecure sets the cookie as Secure.

func (*Cookie) SetValue

func (c *Cookie) SetValue(value string)

SetValue sets the cookie value.

func (*Cookie) Value

func (c *Cookie) Value() string

Value returns the cookie value.

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 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 WrapFastHandler

func WrapFastHandler(handler fasthttp.RequestHandler) Handler

WrapHandler wraps `fasthttp.RequestHandler` into `macross.Handler`.

func WrapHttpHandler

func WrapHttpHandler(handler http.Handler) Handler

WrapHttpHandler is responsible for adapting macross requests through fasthttp interfaces to net/http requests.

Based on valyala/fasthttp implementation. Available here: https://github.com/valyala/fasthttp/blob/master/fasthttpadaptor/adaptor.go

type Localer

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

Localer reprents a localization interface.

type Macross

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

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

func Classic

func Classic() *Macross

New creates a new Classic Macross object.

func New

func New() *Macross

New creates a new Macross object.

func (*Macross) AcquireContext

func (m *Macross) AcquireContext() *Context

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

func (*Macross) Binder

func (m *Macross) Binder() Binder

Binder returns the binder instance.

func (*Macross) File

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

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

func (*Macross) HandleError

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

HandleError is the error handler for handling any unhandled errors.

func (*Macross) Listen

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

func (*Macross) ListenTLS

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

func (*Macross) ListenTLSEmbed

func (m *Macross) ListenTLSEmbed(certData, keyData []byte, args ...interface{})

func (*Macross) Localer

func (m *Macross) Localer() Localer

Localer returns the locale instance.

func (*Macross) NotFound

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

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

func (*Macross) Pull

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

func (*Macross) Push

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

func (*Macross) ReleaseContext

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

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

func (*Macross) Route

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

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

func (*Macross) ServeHTTP

func (m *Macross) ServeHTTP(ctx *fasthttp.RequestCtx)

ServeHTTP handles the HTTP request.

func (*Macross) Sessioner

func (m *Macross) Sessioner() Sessioner

Sessioner returns the sessioner instance.

func (*Macross) SetBinder

func (m *Macross) SetBinder(b Binder)

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

func (*Macross) SetLocaler

func (m *Macross) SetLocaler(l Localer)

SetLocale registers a custom localer.

func (*Macross) SetRenderer

func (m *Macross) SetRenderer(r Renderer)

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

func (*Macross) SetSessioner

func (m *Macross) SetSessioner(s Sessioner)

SetSessioner registers a custom sessioner. It's invoked by `Context#Bind()`.

func (*Macross) Static

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

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

func (*Macross) Use

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

Use appends the specified handlers to the macross 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 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 macross using the CONNECT HTTP method.

func (*Route) Delete

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

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

func (*Route) Get

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

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

func (*Route) Head

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

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

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 macross as well.

func (*Route) Options

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

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

func (*Route) Patch

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

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

func (*Route) Post

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

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

func (*Route) Put

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

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

func (*Route) To

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

To adds the route to the macross 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 macross 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 (r *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 (r *RouteGroup) Connect(path string, handlers ...Handler) *Route

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

func (*RouteGroup) Delete

func (r *RouteGroup) Delete(path string, handlers ...Handler) *Route

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

func (*RouteGroup) Get

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

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

func (*RouteGroup) Group

func (r *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 (r *RouteGroup) Head(path string, handlers ...Handler) *Route

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

func (*RouteGroup) Options

func (r *RouteGroup) Options(path string, handlers ...Handler) *Route

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

func (*RouteGroup) Patch

func (r *RouteGroup) Patch(path string, handlers ...Handler) *Route

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

func (*RouteGroup) Post

func (r *RouteGroup) Post(path string, handlers ...Handler) *Route

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

func (*RouteGroup) Put

func (r *RouteGroup) Put(path string, handlers ...Handler) *Route

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

func (*RouteGroup) To

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

To adds a route to the macross 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 (r *RouteGroup) Trace(path string, handlers ...Handler) *Route

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

func (*RouteGroup) Use

func (r *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 SerializeFunc

type SerializeFunc func(data interface{}) ([]byte, error)

SerializeFunc serializes the given data of arbitrary type into a byte array.

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.

Directories

Path Synopsis
Package access provides an access logging handler for the macross package.
Package access provides an access logging handler for the macross package.
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