faygo

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2018 License: Apache-2.0 Imports: 54 Imported by: 0

README

Faygo report card github issues github closed issues GitHub release GoDoc view Go网络编程群

Faygo Favicon

Faygo is a fast and concise Go Web framework that can be used to develop high-performance web app(especially API) with fewer codes. Just define a struct Handler, Faygo will automatically bind/verify the request parameters and generate the online API doc. Go to <User Manual>

简体中文

faygo index

faygo apidoc

faygo server

Latest version

Version

v1.2.0

Requirements

Go Version ≥ 1.8

Quick Start

  • Way 1: download source
go get -u -v github.com/henrylee2cn/faygo
go get -u -v github.com/henrylee2cn/fay
        fay command [arguments]

The commands are:
        new        create, compile and run (monitor changes) a new faygo project
        run        compile and run (monitor changes) an any existing go project

fay new appname [apptpl]
        appname    specifies the path of the new faygo project
        apptpl     optionally, specifies the faygo project template type

fay run [appname]
        appname    optionally, specifies the path of the new project

Features

  • One struct Handler can get more things:
  • Define Handler/Middleware
  • Bind and verify request parameters
  • Generate an online document for the Swagger 2.0 API
  • Database ORM mapping
  • Handler and Middleware are exactly the same, both implement the Handler interface (func or struct), which together constitute the handler chain of the router.
  • Supports multiple network types:
Network types Configuration net_types
HTTP http
HTTPS/HTTP2(TLS) https
HTTPS/HTTP2(Let's Encrypt TLS) letsencrypt
HTTPS/HTTP2(Let's Encrypt TLS on UNIX socket) unix_letsencrypt
HTTP(UNIX socket) unix_http
HTTPS/HTTP2(TLS on UNIX socket) unix_https
  • Support single-service & single-listener, single-service & multi-listener, multi-service & multi-listener and so on. The config of multiple services is independent of each other.
  • The high-performance router based on httprouter supports both chain and tree registration styles; supports flexible static file router (such as DirFS, RenderFS, MarkdownFS, etc.).
  • Support graceful shutdown and rebooting, provide fay tools which has new projects, hot compilation , meta programming function.
  • Use the most powerful pongo2 as the HTML rendering engine.
  • Support near-LRU memory caching. (mainly used for static file cache)
  • Support cross-platform color log system, and has two output interface(console and file).
  • Support session management.
  • Support global gzip compression config.
  • Support XSRF security filtering.
  • Most features try to use simple ini configs to avoid unnecessary recompilation, and these profiles can be automatically assigned default values.
  • Provide gorm, xorm, sqlx, directSQL, Websocket, ini, http client and many other commonly used expansion packages.

faygo handler multi-usage

Simple example

package main

import (
    // "mime/multipart"
    "time"
    "github.com/henrylee2cn/faygo"
)

type Index struct {
    Id        int      `param:"<in:path> <required> <desc:ID> <range: 0:10>"`
    Title     string   `param:"<in:query> <nonzero>"`
    Paragraph []string `param:"<in:query> <name:p> <len: 1:10> <regexp: ^[\\w]*$>"`
    Cookie    string   `param:"<in:cookie> <name:faygoID>"`
    // Picture         *multipart.FileHeader `param:"<in:formData> <name:pic> <maxmb:30>"`
}

func (i *Index) Serve(ctx *faygo.Context) error {
    if ctx.CookieParam("faygoID") == "" {
        ctx.SetCookie("faygoID", time.Now().String())
    }
    return ctx.JSON(200, i)
}

func main() {
    app := faygo.New("myapp", "0.1")

    // Register the route in a chain style
    app.GET("/index/:id", new(Index))

    // Register the route in a tree style
    // app.Route(
    //     app.NewGET("/index/:id", new(Index)),
    // )

    // Start the service
    faygo.Run()
}

/*
http GET:
    http://localhost:8080/index/1?title=test&p=abc&p=xyz
response:
    {
        "Id": 1,
        "Title": "test",
        "Paragraph": [
            "abc",
            "xyz"
        ],
        "Cookie": "2016-11-13 01:14:40.9038005 +0800 CST"
    }
*/

All samples

Handler and middleware

Handler and middleware are the same, both implemente Handler interface!

  • function type
// Page handler doesn't contains API doc description
func Page() faygo.HandlerFunc {
    return func(ctx *faygo.Context) error {
        return ctx.String(200, "faygo")
    }
}

// Page2 handler contains API doc description
var Page2 = faygo.WrapDoc(Page(), "test page2 notes", "test")
  • struct type
// Param binds and validates the request parameters by Tags
type Param struct {
    Id    int    `param:"<in:path> <required> <desc:ID> <range: 0:10>"`
    Title string `param:"<in:query>"`
}

// Serve implemente Handler interface
func (p *Param) Serve(ctx *faygo.Context) error {
    return ctx.JSON(200,
        faygo.Map{
            "Struct Params":    p,
            "Additional Param": ctx.PathParam("additional"),
        }, true)
}

// Doc implemente API Doc interface (optional)
func (p *Param) Doc() faygo.Doc {
    return faygo.Doc{
        // Add the API notes to the API doc
        Note: "param desc",
        // declare the response content format to the API doc
        Return: faygo.JSONMsg{
            Code: 1,
            Info: "success",
        },
        // additional request parameter declarations to the API doc (optional)
        Params: []faygo.ParamInfo{
            {
                Name:  "additional",
                In:    "path",
                Model: "a",
                Desc:  "defined by the `Doc()` method",
            },
        },
    }
}

Filter function

The filter function must be HandleFunc type!

func Root2Index(ctx *faygo.Context) error {
    // Direct access to `/index` is not allowed
    if ctx.Path() == "/index" {
        ctx.Stop()
        return nil
    }
    if ctx.Path() == "/" {
        ctx.ModifyPath("/index")
    }
    return nil
}

Route registration

  • tree style
// New application object, params: name, version
var app1 = faygo.New("myapp1", "1.0")

// router
app1.Filter(Root2Index).
    Route(
        app1.NewNamedGET("test page", "/page", Page()),
        app1.NewNamedGET("test page2", "/page2", Page2),
        app1.NewGroup("home",
            app1.NewNamedGET("test param", "/param", &Param{
                // sets the default value in the API documentation for the request parameters (optional)
                Id:    1,
                Title: "test param",
            }),
        ),
    )
  • chain style
// New application object, params: name, version
var app2 = faygo.New("myapp2", "1.0")

// router
app2.Filter(Root2Index)
app2.NamedGET("test page", "/page", Page())
app2.NamedGET("test page2", "/page2", Page2)
app2.Group("home")
{
    app2.NamedGET("test param", "/param", &Param{
        // sets the default value in the API documentation for the request parameters(optional)
        Id:    1,
        Title: "test param",
    })
}

Shutdown and reboot

  • shutdown gracefully
kill [pid]
  • reboot gracefully
kill -USR2 [pid]

Configuration

  • Each instance of the application has a single config (file name format config/{appname}[_{version}].ini). Refer to the following:
net_types              = http|https              # List of network type: http | https | unix_http | unix_https | letsencrypt | unix_letsencrypt
addrs                  = 0.0.0.0:80|0.0.0.0:443  # List of multiple listening addresses
tls_certfile           =                         # TLS certificate file path
tls_keyfile            =                         # TLS key file path
letsencrypt_dir        =                         # Let's Encrypt TLS certificate cache directory
unix_filemode          = 0666                    # File permissions for UNIX listener, requires octal number
http_redirect_https    = false                   # Redirect from 'http://hostname:port1' to 'https://hostname:port2'
read_timeout           = 0s                      # Maximum duration for reading the full; ns|µs|ms|s|m|h request (including body)
write_timeout          = 0s                      # Maximum duration for writing the full; ns|µs|ms|s|m|h response (including body)
multipart_maxmemory_mb = 32                      # Maximum size of memory that can be used when receiving uploaded files
slow_response_threshold= 0s                      # When response time > slow_response_threshold, log level   = 'WARNING'; 0 means not limited; ns|µs|ms|s|m|h
print_body             = false                   # Form requests are printed in JSON format, but other types are printed as-is

[router]                                         # Routing config section
redirect_trailing_slash   = true                 # Automatic redirection (for example, `/foo/` -> `/foo`)
redirect_fixed_path       = true                 # Tries to fix the current request path, if no handle is registered for it
handle_method_not_allowed = true                 # Returns 405 if the requested method does not exist, otherwise returns 404
handle_options            = true                 # Automatic response OPTIONS request, you can set the default Handler in Faygo
default_upload            = true                 # Automatically register the default router: /upload/*filepath
default_static            = true                 # Automatically register the default router: /static/*filepath

[xsrf]                                           # XSRF security section
enable        = false                            # Whether enabled or not
key           = faygoxsrf                        # Encryption key
expire_second = 3600                             # Expire of XSRF token

[session]                                        # Session section
enable                 = false                   # Whether enabled or not
provider               = memory                  # Data storage
name                   = faygosessionID          # The client stores the name of the cookie
provider_config        =                         # According to the different engine settings different config information
cookie_life_second     = 0                       # The default value is 0, which is the lifetime of the browser
gc_life_second         = 300                     # The interval between triggering the GC
max_life_second        = 3600                    # The session max lefetime
auto_setcookie         = true                    # Automatically set on the session cookie value, the general default true
domain                 =                         # The domain name that is allowed to access this cookie
enable_sid_in_header   = false                   # Whether to write a session ID to the header
name_in_header         = Faygosessionid          # The name of the header when the session ID is written to the header
enable_sid_in_urlquery = false                   # Whether to write the session ID to the URL Query params

[apidoc]                                         # API documentation section
enable      = true                               # Whether enabled or not
path        = /apidoc                            # The URL path
nolimit     = false                              # If true, access is not restricted
real_ip     = false                              # If true, means verifying the real IP of the visitor
whitelist   = 192.*|202.122.246.170              # `whitelist=192.*|202.122.246.170` means: only IP addresses that are prefixed with `192.` or equal to `202.122.246.170` are allowed
desc        =                                    # Description of the application
email       =                                    # Technician's Email
terms_url   =                                    # Terms of service
license     =                                    # The license used by the API
license_url =                                    # The URL of the protocol content page
  • Only one global config is applied (config/__global__.ini). Refer to the following:
[cache]                                          # Cache section
enable         = false                           # Whether enabled or not
size_mb        = 32                              # Max size by MB for file cache, the cache size will be set to 512KB at minimum.
expire_second  = 60                              # Maximum duration for caching

[gzip]                                           # compression section
enable         = false                           # Whether enabled or not
min_length     = 20                              # The minimum length of content to be compressed
compress_level = 1                               # Non-file response Body's compression level is 0-9, but the files' always 9
methods        = GET                             # List of HTTP methods to compress. If not set, only GET requests are compressed.

[log]                                            # Log section
console_enable = true                            # Whether enabled or not console logger
console_level  = debug                           # Console logger level: critical | error | warning | notice | info | debug
file_enable    = true                            # Whether enabled or not file logger
file_level     = debug                           # File logger level: critical | error | warning | notice | info | debug
async_len      = 0                               # The length of asynchronous buffer, 0 means synchronization

Handler struct tags

tag key required value desc
param in only one path (position of param) if required is unsetted, auto set it. e.g. url: "http://www.abc.com/a/{path}"
param in only one query (position of param) e.g. url: "http://www.abc.com/a?b={query}"
param in only one formData (position of param) e.g. "request body: a=123&b={formData}"
param in only one body (position of param) request body can be any content
param in only one header (position of param) request header info
param in only one cookie (position of param) request cookie info, support: *http.Cookie,http.Cookie,string,[]byte
param name no (e.g.id) specify request param`s name
param required no request param is required
param desc no (e.g.id) request param description
param len no (e.g.3:6) length range [a,b] of param's value
param range no (e.g.0:10) numerical range [a,b] of param's value
param nonzero no param`s value can not be zero
param maxmb no (e.g.32) when request Content-Type is multipart/form-data, the max memory for body.(multi-param, whichever is greater)
param regexp no (e.g.^\\w+$) verify the value of the param with a regular expression(param value can not be null)
param err no (e.g.incorrect password format) the custom error for binding or validating

NOTES:

  • the binding object must be a struct pointer
  • in addition to *multipart.FileHeader, the binding struct's field can not be a pointer
  • if the param tag is not exist, anonymous field will be parsed
  • when the param's position(in) is formData and the field's type is *multipart.FileHeader, multipart.FileHeader, []*multipart.FileHeader or []multipart.FileHeader, the param receives file uploaded
  • if param's position(in) is cookie, field's type must be *http.Cookie or http.Cookie
  • param tags in(formData) and in(body) can not exist at the same time
  • there should not be more than one in(body) param tag

Handler struct fields type

base slice special
string []string [][]byte
byte []byte [][]uint8
uint8 []uint8 *multipart.FileHeader (only for formData param)
bool []bool []*multipart.FileHeader (only for formData param)
int []int *http.Cookie (only for net/http's cookie param)
int8 []int8 http.Cookie (only for net/http's cookie param)
int16 []int16 struct (struct type only for body param or as an anonymous field to extend params)
int32 []int32
int64 []int64
uint8 []uint8
uint16 []uint16
uint32 []uint32
uint64 []uint64
float32 []float32
float64 []float64

Expansion package

package summary import path
barcode github.com/henrylee2cn/faygo/ext/barcode
Bit unit conversion github.com/henrylee2cn/faygo/ext/bitconv
gorm(DB ORM) github.com/henrylee2cn/faygo/ext/db/gorm
sqlx(DB ext) github.com/henrylee2cn/faygo/ext/db/sqlx
xorm(DB ORM) github.com/henrylee2cn/faygo/ext/db/xorm
directSQL(Configured SQL engine) github.com/henrylee2cn/faygo/ext/db/directsql
One-time Password github.com/henrylee2cn/faygo/ext/otp
UUID github.com/henrylee2cn/faygo/ext/uuid
Websocket github.com/henrylee2cn/faygo/ext/websocket
ini github.com/henrylee2cn/faygo/ini
cron github.com/henrylee2cn/faygo/ext/cron
task github.com/henrylee2cn/faygo/ext/task
http client github.com/henrylee2cn/faygo/ext/surfer

Know Cases

Product Name Web/App Server Home Page
盯房 App https://www.df-house.com
eTrade App https://fir.im/ejy
Seven A Jewelry Web http://sevenajewelry.com
OneFor App https://fir.im/eqb
杰运好车 App https://www.jieyunhaoche.com/appdown

Note: Sorted in alphabetical order

License

Faygo is under Apache v2 License. See the LICENSE file for the full license text

Documentation

Overview

Package Faygo is a fast and concise Go Web framework that can be used to develop high-performance web app(especially API) with fewer codes; Just define a struct Handler, Faygo will automatically bind/verify the request parameters and generate the online API doc.

Copyright 2016 HenryLee. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

A trivial example is:

package main

import (
    // "mime/multipart"
    "time"
    "github.com/henrylee2cn/faygo"
)

type Index struct {
    Id        int      `param:"<in:path> <required> <desc:ID> <range: 0:10>"`
    Title     string   `param:"<in:query> <nonzero>"`
    Paragraph []string `param:"<in:query> <name:p> <len: 1:10> <regexp: ^[\\w]*$>"`
    Cookie    string   `param:"<in:cookie> <name:faygoID>"`
    // Picture         *multipart.FileHeader `param:"<in:formData> <name:pic> <maxmb:30>"`
}

func (i *Index) Serve(ctx *faygo.Context) error {
    if ctx.CookieParam("faygoID") == "" {
        ctx.SetCookie("faygoID", time.Now().String())
    }
    return ctx.JSON(200, i)
}

func main() {
    app := faygo.New("myapp", "0.1")

    // Register the route in a chain style
    app.GET("/index/:id", new(Index))

    // Register the route in a tree style
    // app.Route(
    //     app.NewGET("/index/:id", new(Index)),
    // )

    // Start the service
    faygo.Run()
}

run result:

http GET:
http://localhost:8080/index/1?title=test&p=abc&p=xyz
response:
    {
        "Id": 1,
        "Title": "test",
        "Paragraph": [
            "abc",
            "xyz"
        ],
        "Cookie": "2016-11-13 01:14:40.9038005 +0800 CST"
    }

StructHandler tag value description:

tag   |   key    | required |     value     |   desc
------|----------|----------|---------------|----------------------------------
param |    in    | only one |     path      | (position of param) if `required` is unsetted, auto set it. e.g. url: "http://www.abc.com/a/{path}"
param |    in    | only one |     query     | (position of param) e.g. url: "http://www.abc.com/a?b={query}"
param |    in    | only one |     formData  | (position of param) e.g. "request body: a=123&b={formData}"
param |    in    | only one |     body      | (position of param) request body can be any content
param |    in    | only one |     header    | (position of param) request header info
param |    in    | only one |     cookie    | (position of param) request cookie info, support: `*http.Cookie`,`http.Cookie`,`string`,`[]byte`
param |   name   |    no    |   (e.g.`id`)   | specify request param`s name
param | required |    no    |               | request param is required
param |   desc   |    no    |   (e.g.`id`)   | request param description
param |   len    |    no    | (e.g.`3:6` `3`) | length range of param's value
param |   range  |    no    |  (e.g.`0:10`)  | numerical range of param's value
param |  nonzero |    no    |               | param`s value can not be zero
param |   maxmb  |    no    |   (e.g.`32`)   | when request Content-Type is multipart/form-data, the max memory for body.(multi-param, whichever is greater)
param |  regexp  |    no    | (e.g.`^\\w+$`) | verify the value of the param with a regular expression(param value can not be null)
param |   err    |    no    |(e.g.`incorrect password format`)| the custom error for binding or validating

NOTES:
    1. the binding object must be a struct pointer
    2. in addition to `*multipart.FileHeader`, the binding struct's field can not be a pointer
    3. `regexp` or `param` tag is only usable when `param:"type(xxx)"` is exist
    4. if the `param` tag is not exist, anonymous field will be parsed
    5. when the param's position(`in`) is `formData` and the field's type is `*multipart.FileHeader`, `multipart.FileHeader`, `[]*multipart.FileHeader` or `[]multipart.FileHeader`, the param receives file uploaded
    6. if param's position(`in`) is `cookie`, field's type must be `*http.Cookie` or `http.Cookie`
    7. param tags `in(formData)` and `in(body)` can not exist at the same time
    8. there should not be more than one `in(body)` param tag

List of supported param value types:

base    |   slice    | special
--------|------------|-------------------------------------------------------
string  |  []string  | [][]byte
byte    |  []byte    | [][]uint8
uint8   |  []uint8   | *multipart.FileHeader (only for `formData` param)
bool    |  []bool    | []*multipart.FileHeader (only for `formData` param)
int     |  []int     | *http.Cookie (only for `net/http`'s `cookie` param)
int8    |  []int8    | http.Cookie (only for `net/http`'s `cookie` param)
int16   |  []int16   | struct (struct type only for `body` param or as an anonymous field to extend params)
int32   |  []int32   |
int64   |  []int64   |
uint8   |  []uint8   |
uint16  |  []uint16  |
uint32  |  []uint32  |
uint64  |  []uint64  |
float32 |  []float32 |
float64 |  []float64 |

Index

Constants

View Source
const (
	// RUNMODE_DEV                 = "dev"
	// RUNMODE_PROD                = "prod"
	MB = 1 << 20 // 1MB

	// The path for the config files
	CONFIG_DIR = "./config/"
	// global config file name
	GLOBAL_CONFIG_FILE = "__global___.ini"
)

some default config

View Source
const (
	HeaderAccept                        = "Accept"
	HeaderAcceptEncoding                = "Accept-Encoding"
	HeaderAuthorization                 = "Authorization"
	HeaderContentDisposition            = "Content-Disposition"
	HeaderContentEncoding               = "Content-Encoding"
	HeaderContentLength                 = "Content-Length"
	HeaderContentType                   = "Content-Type"
	HeaderContentDescription            = "Content-Description"
	HeaderContentTransferEncoding       = "Content-Transfer-Encoding"
	HeaderCookie                        = "Cookie"
	HeaderSetCookie                     = "Set-Cookie"
	HeaderIfModifiedSince               = "If-Modified-Since"
	HeaderLastModified                  = "Last-Modified"
	HeaderLocation                      = "Location"
	HeaderReferer                       = "Referer"
	HeaderUserAgent                     = "User-Agent"
	HeaderUpgrade                       = "Upgrade"
	HeaderVary                          = "Vary"
	HeaderWWWAuthenticate               = "WWW-Authenticate"
	HeaderXForwardedProto               = "X-Forwarded-Proto"
	HeaderXHTTPMethodOverride           = "X-HTTP-Method-Override"
	HeaderXForwardedFor                 = "X-Forwarded-For"
	HeaderXRealIP                       = "X-Real-IP"
	HeaderXRequestedWith                = "X-Requested-With"
	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"
	HeaderExpires                       = "Expires"
	HeaderCacheControl                  = "Cache-Control"
	HeaderPragma                        = "Pragma"

	// 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 (
	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 (
	// listenAndServe listens on the TCP network address and then
	// calls Serve to handle requests on incoming connections.
	// Accepted connections are configured to enable TCP keep-alives.
	// If srv.Addr is blank, ":http" is used.
	NETTYPE_HTTP = "http"
	// NETTYPE_HTTPS listens on the TCP network address and
	// then calls Serve to handle requests on incoming TLS connections.
	// Accepted connections are configured to enable TCP keep-alives.
	//
	// Filenames containing a certificate and matching private key for the
	// server must be provided if neither the Server's TLSConfig.Certificates
	// nor TLSConfig.GetCertificate are populated. If the certificate is
	// signed by a certificate authority, the certFile should be the
	// concatenation of the server's certificate, any intermediates, and
	// the CA's certificate.
	//
	// If server.Addr is blank, ":https" is used.
	NETTYPE_HTTPS = "https"
	// NETTYPE_LETSENCRYPT listens on a new Automatic TLS using letsencrypt.org service.
	// if you want to disable cache directory then simple give config `letsencrypt_dir` a value of empty string "".
	//
	// If server.Addr is blank, ":https" is used.
	NETTYPE_LETSENCRYPT = "letsencrypt"
	// NETTYPE_UNIX_LETSENCRYPT listens on a new Automatic TLS using letsencrypt.org Unix service.
	// if you want to disable cache directory then simple give config `letsencrypt_dir` a value of empty string "".
	//
	// If server.Addr is blank, ":https" is used.
	NETTYPE_UNIX_LETSENCRYPT = "unix_letsencrypt"
	// NETTYPE_UNIX_HTTP announces on the Unix domain socket addr and listens a Unix service.
	//
	// If server.Addr is blank, ":http" is used.
	NETTYPE_UNIX_HTTP = "unix_http"
	// NETTYPE_UNIX_HTTPS announces on the Unix domain socket addr and listens a secure Unix service.
	//
	// If server.Addr is blank, ":https" is used.
	NETTYPE_UNIX_HTTPS = "unix_https"
)

network types

View Source
const FilepathKey = "filepath"

FilepathKey path key for static router pattern.

View Source
const MinShutdownTimeout = 5 * time.Second

MinShutdownTimeout the default time-out period for the services shutdown.

View Source
const (
	// TAG_PARAM param tag
	TAG_PARAM = apiware.TAG_PARAM
)
View Source
const (
	// VERSION is faygo web framework's version
	VERSION = "1.2.0"
)

Variables

View Source
var (
	ErrNotStructPtr   = errors.New("handler must be a structure type or a structure pointer type")
	ErrNoParamHandler = errors.New("handler does not define any parameter tags")
)

common errors

View Source
var BytesToString = goutil.BytesToString

BytesToString convert []byte type to string type.

func BytesToString(b []byte) string
View Source
var CamelString = goutil.CamelString

CamelString converts the accepted string to a camel string (xx_yy to XxYy)

func CamelString(s string) string
View Source
var FileExists = goutil.FileExists

FileExists reports whether the named file or directory exists.

func FileExists(name string) bool
View Source
var GrepFile = goutil.GrepFile

GrepFile like command grep -E for example: GrepFile(`^hello`, "hello.txt") \n is striped while read

func GrepFile(patten string, filename string) (lines []string, err error)
View Source
var JsQueryEscape = goutil.JsQueryEscape

JsQueryEscape escapes the string in javascript standard so it can be safely placed inside a URL query.

func JsQueryEscape(s string) string
View Source
var JsQueryUnescape = goutil.JsQueryUnescape

JsQueryUnescape does the inverse transformation of JsQueryEscape, converting %AB into the byte 0xAB and '+' into ' ' (space). It returns an error if any % is not followed by two hexadecimal digits.

func JsQueryUnescape(s string) (string, error)
View Source
var ObjectName = goutil.ObjectName

ObjectName gets the type name of the object

func ObjectName(i interface{}) string
View Source
var RESTfulMethodList = []string{
	"CONNECT",
	"DELETE",
	"GET",
	"HEAD",
	"OPTIONS",
	"PATCH",
	"POST",
	"PUT",
	"TRACE",
}

RESTfulMethodList is the list of all RESTful methods

View Source
var RandomString = goutil.URLRandomString

RandomString returns a URL-safe, base64 encoded securely generated random string. It will panic if the system's secure random number generator fails to function correctly. The length n must be an integer multiple of 4, otherwise the last character will be padded with `=`.

func RandomString(n int) string
View Source
var RelPath = goutil.RelPath

RelPath gets relative path.

func RelPath() string
View Source
var SearchFile = goutil.SearchFile

SearchFile Search a file in paths. this is often used in search config file in /etc ~/

func SearchFile(filename string, paths ...string) (fullpath string, err error)
View Source
var SelfChdir = goutil.SelfChdir

SelfChdir switch the working path to my own path.

func SelfChdir()
View Source
var SelfDir = goutil.SelfDir

SelfDir gets compiled executable file directory

func SelfDir() string
View Source
var SelfPath = goutil.SelfPath

SelfPath gets compiled executable file absolute path.

func SelfPath() string
View Source
var SnakeString = goutil.SnakeString

SnakeString converts the accepted string to a snake string (XxYy to xx_yy)

func SnakeString(s string) string
View Source
var StringToBytes = goutil.StringToBytes

StringToBytes convert string type to []byte type. NOTE: panic if modify the member value of the []byte.

func StringToBytes(s string) []byte
View Source
var WalkDirs = goutil.WalkDirs

WalkDirs traverses the directory, return to the relative path. You can specify the suffix.

func WalkDirs(targpath string, suffixes ...string) (dirlist []string)

Functions

func CleanToURL

func CleanToURL(p string) string

CleanToURL is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.

The following rules are applied iteratively until no further processing can be done:

  1. Replace multiple slashes with a single slash.
  2. Eliminate each . path name element (the current directory).
  3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.

If the result of this process is an empty string, "/" is returned

func CloseLog

func CloseLog()

CloseLog closes global loggers.

func ContentTypeByExtension

func ContentTypeByExtension(ext string) string

ContentTypeByExtension gets the content type from ext string. MIME type is given in mime package. It returns `application/octet-stream` incase MIME type is not found.

func Critical

func Critical(args ...interface{})

Critical logs a message using CRITICAL as log level.

func Criticalf

func Criticalf(format string, args ...interface{})

Criticalf logs a message using CRITICAL as log level.

func Debug

func Debug(args ...interface{})

Debug logs a message using DEBUG as log level.

func Debugf

func Debugf(format string, args ...interface{})

Debugf logs a message using DEBUG as log level.

func DecodeBody

func DecodeBody(dest reflect.Value, body []byte) error

DecodeBody decodes params from request body.

func Error

func Error(args ...interface{})

Error logs a message using ERROR as log level.

func Errorf

func Errorf(format string, args ...interface{})

Errorf logs a message using ERROR as log level.

func Fatal

func Fatal(args ...interface{})

Fatal is equivalent to l.Critical(fmt.Sprint()) followed by a call to os.Exit(1).

func Fatalf

func Fatalf(format string, args ...interface{})

Fatalf is equivalent to l.Critical followed by a call to os.Exit(1).

func HandleBinderror

func HandleBinderror(ctx *Context, err error)

HandleBinderror calls the default parameter binding failure handler.

func HandleError

func HandleError(ctx *Context, errStr string, status int)

HandleError calls the default error handler.

func Info

func Info(args ...interface{})

Info logs a message using INFO as log level.

func Infof

func Infof(format string, args ...interface{})

Infof logs a message using INFO as log level.

func IsHandlerWithoutPath

func IsHandlerWithoutPath(handler Handler) bool

IsHandlerWithoutPath verifies that the Handler is an HandlerWithoutPath.

func JoinStatic

func JoinStatic(shortFilename string) string

JoinStatic adds the static directory prefix to the file name.

func LogDir

func LogDir() string

LogDir returns logs folder path with a slash at the end

func MapParamName

func MapParamName(fieldName string) (paramName string)

MapParamName maps the APIHander's parameter name from the structure field. When the APIHander's parameter name (struct tag) is unsetted, it is mapped from the structure field name by default. If `paramNameMapper` is nil, use snake style.

func NewLog

func NewLog() *logging.Logger

NewLog gets a global logger

func Notice

func Notice(args ...interface{})

Notice logs a message using NOTICE as log level.

func Noticef

func Noticef(format string, args ...interface{})

Noticef logs a message using NOTICE as log level.

func Panic

func Panic(args ...interface{})

Panic is equivalent to l.Critical(fmt.Sprint()) followed by a call to panic().

func Panicf

func Panicf(format string, args ...interface{})

Panicf is equivalent to l.Critical followed by a call to panic().

func Print

func Print(args ...interface{})

Print logs a message using CRITICAL as log level, only with time prefix.

func Printf

func Printf(format string, args ...interface{})

Printf logs a message using CRITICAL as log level, only with time prefix.

func Reboot

func Reboot(timeout ...time.Duration)

Reboot all the frame services gracefully. Notes: Windows system are not supported!

func RemoveUseless

func RemoveUseless()

RemoveUseless when there's not frame instance, remove files: config, log, static and upload .

func RenderVar

func RenderVar(name string, v interface{})

RenderVar sets the global template variable, function or pongo2.FilterFunction for pongo2 render.

func Run

func Run()

Run starts all web services.

func Running

func Running(name string, version ...string) bool

Running returns whether the frame service is running.

func SetBinderrorFunc

func SetBinderrorFunc(binderrorFunc BinderrorFunc)

SetBinderrorFunc sets the global default `BinderrorFunc` function.

func SetBodydecoder

func SetBodydecoder(bodydecoder apiware.Bodydecoder)

SetBodydecoder sets the global default `Bodydecoder` function.

func SetErrorFunc

func SetErrorFunc(errorFunc ErrorFunc)

SetErrorFunc sets the global default `ErrorFunc` function.

func SetParamNameMapper

func SetParamNameMapper(paramNameMapper apiware.ParamNameMapper)

SetParamNameMapper sets the global default `ParamNameMapper` function.

func SetShutdown

func SetShutdown(timeout time.Duration, preCloseFunc, postCloseFunc func() error)

SetShutdown sets the function which is called after the services shutdown, and the time-out period for the services shutdown. If 0<=timeout<5s, automatically use 'MinShutdownTimeout'(5s). If timeout<0, indefinite period. 'preCloseFunc' is executed before closing services, but not guaranteed to be completed. 'postCloseFunc' is executed after services are closed, but not guaranteed to be completed.

func SetStatic

func SetStatic(dir string, nocompress bool, nocache bool, handlers ...Handler)

SetStatic sets static folder path, such as `./staic/` with a slash `/` at the end. note: it should be called before Run()

func SetUpload

func SetUpload(dir string, nocompress bool, nocache bool, handlers ...Handler)

SetUpload sets upload folder path such as `./upload/` with a slash `/` at the end. note: it should be called before Run()

func Shutdown

func Shutdown(timeout ...time.Duration)

Shutdown closes all the frame services gracefully. Parameter timeout is used to reset time-out period for the services shutdown.

func StaticDir

func StaticDir() string

StaticDir returns static folder path with a slash at the end

func SyncINI

func SyncINI(structPtr interface{}, f func(onecUpdateFunc func() error) error, filename ...string) error

SyncINI quickly create your own configuration files. Struct tags reference `https://github.com/go-ini/ini`

func ToAPIHandler

func ToAPIHandler(handler Handler) (*apiHandler, error)

ToAPIHandler tries converts it to an *apiHandler.

func UploadDir

func UploadDir() string

UploadDir returns upload folder path with a slash at the end

func Warning

func Warning(args ...interface{})

Warning logs a message using WARNING as log level.

func Warningf

func Warningf(format string, args ...interface{})

Warningf logs a message using WARNING as log level.

func WritePid

func WritePid(pidFilename string) error

WritePid write pid to the specified file.

Types

type APIDoc

type APIDoc interface {
	Doc() Doc
}

APIDoc provides the API's note, result or parameters information.

type APIHandler

type APIHandler interface {
	Handler
	APIDoc
}

APIHandler is the Faygo Handler interface, which is implemented by a struct with API descriptor information. It is an intelligent Handler of binding parameters.

type APIdocConfig

type APIdocConfig struct {
	Enable     bool     `ini:"enable" comment:"Whether enabled or not"`
	Path       string   `ini:"path" comment:"The URL path"`
	NoLimit    bool     `ini:"nolimit" comment:"If true, access is not restricted"`
	RealIP     bool     `ini:"real_ip" comment:"if true, means verifying the real IP of the visitor"`
	Whitelist  []string `` /* 166-byte string literal not displayed */
	Desc       string   `ini:"desc" comment:"Description of the application"`
	Email      string   `ini:"email" comment:"Technician's Email"`
	TermsURL   string   `ini:"terms_url" comment:"Terms of service"`
	License    string   `ini:"license" comment:"The license used by the API"`
	LicenseURL string   `ini:"license_url" comment:"The URL of the protocol content page"`
}

APIdocConfig is the config about API doc

func (*APIdocConfig) Comb

func (conf *APIdocConfig) Comb()

Comb combs APIdoc config

type BinderrorFunc

type BinderrorFunc func(ctx *Context, err error)

BinderrorFunc is called when binding or validation apiHandler parameters are wrong.

type Bodydecoder

type Bodydecoder interface {
	Decode(dest reflect.Value, body []byte) error
}

Bodydecoder is an interface to customize decoding operation

type CacheConfig

type CacheConfig struct {
	// Whether to enable caching static files
	Enable bool `ini:"enable" comment:"Whether enabled or not"`
	// Max size by MB for file cache.
	// The cache size will be set to 512KB at minimum.
	// If the size is set relatively large, you should call
	// `debug.SetGCPercent()`, set it to a much smaller value
	// to limit the memory consumption and GC pause time.
	SizeMB int64 `ini:"size_mb" comment:"Max size by MB for file cache, the cache size will be set to 512KB at minimum."`
	// expire in xxx seconds for file cache.
	// ExpireSecond <= 0 (second) means no expire, but it can be evicted when cache is full.
	ExpireSecond int `ini:"expire_second" comment:"Maximum duration for caching"`
}

CacheConfig is the config about cache

type CacheFile

type CacheFile struct {
	*bytes.Reader
	// contains filtered or unexported fields
}

CacheFile implements os.File

func NewFile

func NewFile(b []byte, fileInfo os.FileInfo) *CacheFile

NewFile creates a cacheFile

func (*CacheFile) Close

func (c *CacheFile) Close() error

Close closes file

func (*CacheFile) Readdir

func (c *CacheFile) Readdir(count int) ([]os.FileInfo, error)

Readdir gets path info

func (*CacheFile) Stat

func (c *CacheFile) Stat() (os.FileInfo, error)

Stat returns file info

type Config

type Config struct {
	// RunMode         string      `ini:"run_mode" comment:"run mode: dev|prod"`
	NetTypes       []string `ini:"net_types" delim:"|" comment:"List of network type: http|https|unix_http|unix_https|letsencrypt|unix_letsencrypt"`
	Addrs          []string `ini:"addrs" delim:"|" comment:"List of multiple listening addresses"`
	TLSCertFile    string   `ini:"tls_certfile" comment:"TLS certificate file path"`
	TLSKeyFile     string   `ini:"tls_keyfile" comment:"TLS key file path"`
	LetsencryptDir string   `ini:"letsencrypt_dir" comment:"Let's Encrypt TLS certificate cache directory"`
	UNIXFileMode   string   `ini:"unix_filemode" comment:"File permissions for UNIX listener, requires octal number"`

	HttpRedirectHttps bool `ini:"http_redirect_https" comment:"Redirect from 'http://hostname:port1' to 'https://hostname:port2'"`
	// Maximum duration for reading the full request (including body).
	//
	// This also limits the maximum duration for idle keep-alive
	// connections.
	//
	// By default request read timeout is unlimited.
	ReadTimeout time.Duration `ini:"read_timeout" comment:"Maximum duration for reading the full request (including body); ns|µs|ms|s|m|h"`
	// Maximum duration for writing the full response (including body).
	//
	// By default response write timeout is unlimited.
	WriteTimeout         time.Duration `ini:"write_timeout" comment:"Maximum duration for writing the full response (including body); ns|µs|ms|s|m|h"`
	MultipartMaxMemoryMB int64         `ini:"multipart_maxmemory_mb" comment:"Maximum size of memory that can be used when receiving uploaded files"`

	Router                RouterConfig  `ini:"router" comment:"Routing config section"`
	XSRF                  XSRFConfig    `ini:"xsrf" comment:"XSRF security section"`
	Session               SessionConfig `ini:"session" comment:"Session section"`
	SlowResponseThreshold time.Duration `` /* 145-byte string literal not displayed */

	PrintBody bool         `ini:"print_body" comment:"Form requests are printed in JSON format, but other types are printed as-is"`
	APIdoc    APIdocConfig `ini:"apidoc" comment:"API documentation section"`
	// contains filtered or unexported fields
}

Config is the config information for each web instance

func NewDefaultConfig

func NewDefaultConfig() *Config

NewDefaultConfig creates a new default framework config.

type Context

type Context struct {
	R *http.Request // the *http.Request
	W *Response     // the *Response cooked by the http.ResponseWriter
	// contains filtered or unexported fields
}

Context is resetting every time a ruest is coming to the server it is not good practice to use this object in goroutines, for these cases use the .Clone()

func (*Context) AcceptHTML

func (ctx *Context) AcceptHTML() bool

AcceptHTML Checks if request accepts html response

func (*Context) AcceptJSON

func (ctx *Context) AcceptJSON() bool

AcceptJSON Checks if request accepts json response

func (*Context) AcceptXML

func (ctx *Context) AcceptXML() bool

AcceptXML Checks if request accepts xml response

func (*Context) BindBizParam

func (ctx *Context) BindBizParam(dest interface{}, key string) error

BindBizParam data from ctx.BizParam(key) to dest

like /?id=123&isok=true&ft=1.2&ol[0]=1&ol[1]=2&ul[]=str&ul[]=array&user.Name=abc
var id int  ctx.BindBizParam(&id, "id")  id ==123
var isok bool  ctx.BindBizParam(&isok, "isok")  isok ==true
var ft float64  ctx.BindBizParam(&ft, "ft")  ft ==1.2
ol := make([]int, 0, 2)  ctx.BindBizParam(&ol, "ol")  ol ==[1 2]
ul := make([]string, 0, 2)  ctx.BindBizParam(&ul, "ul")  ul ==[str array]
user struct{Name}  ctx.BindBizParam(&user, "user")  user == {Name:"abc"}

func (*Context) BindForm

func (ctx *Context) BindForm(structObject interface{}) error

BindForm reads form data from request's body

func (*Context) BindJSON

func (ctx *Context) BindJSON(jsonObject interface{}) error

BindJSON reads JSON from request's body

func (*Context) BindXML

func (ctx *Context) BindXML(xmlObject interface{}) error

BindXML reads XML from request's body

func (*Context) BizParam

func (ctx *Context) BizParam(key string) string

BizParam returns the first value for the kinds of business parameters. priority: path parameters > POST and PUT body parameters > URL query string values.

BizParam calls ParseMultipartForm and ParseForm if necessary and ignores any errors returned by these functions. If key is not present, BizParam returns the empty string. To access multiple values of the same key, call ParseForm and then inspect Request.Form directly.

func (*Context) Bytes

func (ctx *Context) Bytes(status int, contentType string, content []byte) error

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

func (*Context) Committed

func (ctx *Context) Committed() bool

Committed returns whether the response has been submitted or not.

func (*Context) CookieParam

func (ctx *Context) CookieParam(key string) string

CookieParam returns request cookie item string by a given key. if non-existed, return empty string.

func (*Context) Data

func (ctx *Context) Data(key interface{}) interface{}

Data returns the stored data in this context.

func (*Context) DataAll

func (ctx *Context) DataAll() map[interface{}]interface{}

DataAll return the implicit data in the context

func (*Context) Del

func (ctx *Context) Del(key interface{})

Del delete data by key.

func (*Context) DelSession

func (ctx *Context) DelSession(key interface{})

DelSession removes value from session.

func (*Context) DestroySession

func (ctx *Context) DestroySession()

DestroySession cleans session data and session cookie.

func (*Context) Domain

func (ctx *Context) Domain() string

Domain returns domain as `www.example.com` style.

func (*Context) Error

func (ctx *Context) Error(status int, errStr string)

Send error message and stop handler chain.

func (*Context) File

func (ctx *Context) File(localFilename string, showFilename ...string)

File forces response for download file. it prepares the download response header automatically.

func (*Context) FormFile

func (ctx *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

FormFile returns the first file for the provided form key. FormFile calls ParseMultipartForm and ParseForm if necessary.

func (*Context) FormParam

func (ctx *Context) FormParam(key string) string

FormParam returns the first value for the named component of the POST or PUT ruest body. URL query parameters and path parameters are ignored. FormParam calls ParseMultipartForm and ParseForm if necessary and ignores any errors returned by these functions. If key is not present, FormParam returns the empty string.

func (*Context) FormParamAll

func (ctx *Context) FormParamAll() url.Values

FormParamAll returns the parsed form data from POST, PATCH, or PUT body parameters.

func (*Context) FormParams

func (ctx *Context) FormParams(key string) []string

FormParams returns the form field value with "[]string" for the provided key.

func (*Context) GetSession

func (ctx *Context) GetSession(key interface{}) interface{}

GetSession gets value from session.

func (*Context) HTML

func (ctx *Context) HTML(status int, html string) error

HTML sends an HTTP response with status code.

func (*Context) HasData

func (ctx *Context) HasData(key interface{}) bool

HasData checks if the key exists in the context.

func (*Context) HasFormFile

func (ctx *Context) HasFormFile(key string) bool

HasFormFile returns if the file header for the provided form key is exist.

func (*Context) HeaderParam

func (ctx *Context) HeaderParam(key string) string

HeaderParam gets the first header value associated with the given key. If there are no values associated with the key, HeaderParam returns the empty string.

func (*Context) HeaderParamAll

func (ctx *Context) HeaderParamAll() http.Header

HeaderParamAll returns the whole ruest header.

func (*Context) Host

func (ctx *Context) Host() string

Host returns a host:port string for this request, such as "www.example.com" or "www.example.com:8080".

func (*Context) IP

func (ctx *Context) IP() string

IP gets just the ip from the most direct one client.

func (*Context) Is

func (ctx *Context) Is(method string) bool

Is returns boolean of this request is on given method, such as Is("POST").

func (*Context) IsAjax

func (ctx *Context) IsAjax() bool

IsAjax returns boolean of this request is generated by ajax.

func (*Context) IsBreak

func (ctx *Context) IsBreak() bool

IsBreak returns whether the operation is stopped halfway.

func (*Context) IsCachable

func (ctx *Context) IsCachable() bool

IsCachable returns boolean of this request is cached. HTTP 304 means cached.

func (*Context) IsClientError

func (ctx *Context) IsClientError() bool

IsClientError returns boolean of this request client sends error data. HTTP 4xx means forbidden.

func (*Context) IsDelete

func (ctx *Context) IsDelete() bool

IsDelete Is this a DELETE method request?

func (*Context) IsEmpty

func (ctx *Context) IsEmpty() bool

IsEmpty returns boolean of this request is empty. HTTP 201,204 and 304 means empty.

func (*Context) IsForbidden

func (ctx *Context) IsForbidden() bool

IsForbidden returns boolean of this request is forbidden. HTTP 403 means forbidden.

func (*Context) IsGet

func (ctx *Context) IsGet() bool

IsGet Is this a GET method request?

func (*Context) IsHead

func (ctx *Context) IsHead() bool

IsHead Is this a Head method request?

func (*Context) IsNotFound

func (ctx *Context) IsNotFound() bool

IsNotFound returns boolean of this request is not found. HTTP 404 means forbidden.

func (*Context) IsOk

func (ctx *Context) IsOk() bool

IsOk returns boolean of this request runs well. HTTP 200 means ok.

func (*Context) IsOptions

func (ctx *Context) IsOptions() bool

IsOptions Is this a OPTIONS method request?

func (*Context) IsPatch

func (ctx *Context) IsPatch() bool

IsPatch Is this a PATCH method request?

func (*Context) IsPost

func (ctx *Context) IsPost() bool

IsPost Is this a POST method request?

func (*Context) IsPut

func (ctx *Context) IsPut() bool

IsPut Is this a PUT method request?

func (*Context) IsRedirect

func (ctx *Context) IsRedirect() bool

IsRedirect returns boolean of this request is redirection header. HTTP 301,302,307 means redirection.

func (*Context) IsSecure

func (ctx *Context) IsSecure() bool

IsSecure returns boolean of this request is in https.

func (*Context) IsServerError

func (ctx *Context) IsServerError() bool

IsServerError returns boolean of this server handler errors. HTTP 5xx means server internal error.

func (*Context) IsSuccessful

func (ctx *Context) IsSuccessful() bool

IsSuccessful returns boolean of this request runs successfully. HTTP 2xx means ok.

func (*Context) IsUpload

func (ctx *Context) IsUpload() bool

IsUpload returns boolean of whether file uploads in this request or not..

func (*Context) IsWebsocket

func (ctx *Context) IsWebsocket() bool

IsWebsocket returns boolean of this request is in webSocket.

func (*Context) JSON

func (ctx *Context) JSON(status int, data interface{}, isIndent ...bool) error

JSON sends a JSON response with status code.

func (*Context) JSONBlob

func (ctx *Context) JSONBlob(status int, b []byte) error

JSONBlob sends a JSON blob response with status code.

func (*Context) JSONMsg

func (ctx *Context) JSONMsg(status int, msgcode int, info interface{}, isIndent ...bool) error

JSONMsg sends a JSON with JSONMsg format.

func (*Context) JSONOrXML

func (ctx *Context) JSONOrXML(status int, data interface{}, isIndent ...bool) error

JSONOrXML serve Xml OR Json, depending on the value of the Accept header

func (*Context) JSONP

func (ctx *Context) JSONP(status int, callback string, data interface{}, isIndent ...bool) error

JSONP sends a JSONP response with status code. It uses `callback` to construct the JSONP payload.

func (*Context) LimitedBodyBytes

func (ctx *Context) LimitedBodyBytes() []byte

LimitedBodyBytes returns the raw request body data as bytes. Note:

1.limited by maximum length;
2.if frame.config.PrintBody==false and ctx.R.Body is readed, returns nil;
3.if ctx.IsUpload()==true and ctx.R.Body is readed, returns nil.

func (*Context) Log

func (ctx *Context) Log() *logging.Logger

Log used by the user bissness

func (*Context) Method

func (ctx *Context) Method() string

Method returns http request method.

func (*Context) ModifyPath

func (ctx *Context) ModifyPath(p string)

ModifyPath modifies the access path for the request.

func (*Context) Next

func (ctx *Context) Next()

Next calls all the next handler from the middleware stack, it used inside a middleware. Notes: Non-concurrent security.

func (*Context) NoContent

func (ctx *Context) NoContent(status int)

NoContent sends a response with no body and a status code.

func (*Context) Param

func (ctx *Context) Param(key string) string

Param returns the first value for the kinds of parameters. priority: path parameters > POST and PUT body parameters > URL query string values > header > cookie.Value.

Param calls ParseMultipartForm and ParseForm if necessary and ignores any errors returned by these functions. If key is not present, Param returns the empty string. To access multiple values of the same key, call ParseForm and then inspect Request.Form directly.

func (*Context) ParseFormOrMulitForm

func (ctx *Context) ParseFormOrMulitForm(maxMemory int64) error

ParseFormOrMulitForm parseForm or parseMultiForm based on Content-type

func (*Context) Path

func (ctx *Context) Path() string

Path returns request url path (without query string, fragment).

func (*Context) PathParam

func (ctx *Context) PathParam(key string) string

PathParam returns path param by key.

func (*Context) PathParamAll

func (ctx *Context) PathParamAll() PathParams

PathParamAll returns whole path parameters.

func (*Context) Port

func (ctx *Context) Port() int

Port returns the port number of request.

func (*Context) Protocol

func (ctx *Context) Protocol() string

Protocol returns request protocol name, such as HTTP/1.1 .

func (*Context) Proxy

func (ctx *Context) Proxy() []string

Proxy returns proxy client ips slice.

func (*Context) QueryParam

func (ctx *Context) QueryParam(key string) string

QueryParam gets the first query value associated with the given key. If there are no values associated with the key, QueryParam returns the empty string.

func (*Context) QueryParamAll

func (ctx *Context) QueryParamAll() url.Values

QueryParamAll returns all query params.

func (*Context) QueryParams

func (ctx *Context) QueryParams(key string) []string

QueryParams returns the query param with "[]string".

func (*Context) RealIP

func (ctx *Context) RealIP() string

RealIP returns request client ip. if in proxy, return first proxy id. if error, return 127.0.0.1.

func (*Context) Redirect

func (ctx *Context) Redirect(status int, urlStr string) error

Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

The provided status code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.

func (*Context) Referer

func (ctx *Context) Referer() string

Referer returns http referer header.

func (*Context) Render

func (ctx *Context) Render(status int, name string, data Map) error

Render renders a template with data and sends a text/html response with status code.

func (*Context) ReverseProxy

func (ctx *Context) ReverseProxy(targetUrlBase string, pathAppend bool) error

ReverseProxy routes URLs to the scheme, host, and base path provided in targetUrlBase. If pathAppend is "true" and the targetUrlBase's path is "/base" and the incoming ruest was for "/dir", the target ruest will be for /base/dir.

func (*Context) SaveFile

func (ctx *Context) SaveFile(key string, cover bool, newfname ...string) (savedFileInfo SavedFileInfo, err error)

SaveFile saves the uploaded file to global.UploadDir(), character "?" indicates that the original file name. for example newfname="a/?" -> global.UploadDir()/a/fname.

func (*Context) SaveFiles

func (ctx *Context) SaveFiles(key string, cover bool, newfname ...string) (savedFileInfos []SavedFileInfo, err error)

SaveFiles saves the uploaded files to global.UploadDir(), it's similar to SaveFile, but for saving multiple files.

func (*Context) Scheme

func (ctx *Context) Scheme() string

Scheme returns request scheme as "http" or "https".

func (*Context) SecureCookieParam

func (ctx *Context) SecureCookieParam(secret, key string) (string, bool)

SecureCookieParam Get secure cookie from request by a given key.

func (*Context) SessionRegenerateID

func (ctx *Context) SessionRegenerateID()

SessionRegenerateID regenerates session id for this session. the session data have no changes.

func (*Context) SetCookie

func (ctx *Context) SetCookie(name string, value string, others ...interface{})

SetCookie sets cookie value via given key. others are ordered as cookie's max age time, path, domain, secure and httponly.

func (*Context) SetData

func (ctx *Context) SetData(key, val interface{})

SetData stores data with given key in this context. This data are only available in this context.

func (*Context) SetHeader

func (ctx *Context) SetHeader(key, val string)

SetHeader sets response header item string via given key.

func (*Context) SetSecureCookie

func (ctx *Context) SetSecureCookie(secret, name, value string, others ...interface{})

SetSecureCookie Set Secure cookie for response.

func (*Context) SetSession

func (ctx *Context) SetSession(key interface{}, value interface{})

SetSession puts value into session.

func (*Context) Site

func (ctx *Context) Site() string

Site returns base site url as `scheme://domain:port` type.

func (*Context) Size

func (ctx *Context) Size() int64

Size returns the current size, in bytes, of the response.

func (*Context) Status

func (ctx *Context) Status() int

Status returns the HTTP status code of the response.

func (*Context) Stop

func (ctx *Context) Stop()

Stop just sets the .pos to 32766 in order to not move to the next handlers(if any)

func (*Context) Stopped

func (ctx *Context) Stopped() bool

Stopped returns whether the operation has stopped.

func (*Context) String

func (ctx *Context) String(status int, format string, s ...interface{}) error

String writes a string to the client, something like fmt.Fprintf

func (*Context) URI

func (ctx *Context) URI() string

URI returns full request url with query string, fragment.

func (*Context) URL

func (ctx *Context) URL() *url.URL

URL returns full request url with query string, fragment.

func (*Context) UserAgent

func (ctx *Context) UserAgent() string

UserAgent returns request client user agent string.

func (*Context) XML

func (ctx *Context) XML(status int, data interface{}, isIndent ...bool) error

XML sends an XML response with status code.

func (*Context) XMLBlob

func (ctx *Context) XMLBlob(status int, b []byte) error

XMLBlob sends a XML blob response with status code.

func (*Context) XSRFFormHTML

func (ctx *Context) XSRFFormHTML() string

XSRFFormHTML writes an input field contains xsrf token value.

func (*Context) XSRFToken

func (ctx *Context) XSRFToken(specifiedExpiration ...int) string

XSRFToken creates a xsrf token string and returns. If specifiedExpiration is empty, the value in the configuration is used.

type Doc

type Doc struct {
	Note   string      `json:"note" xml:"note"`
	Return interface{} `json:"return,omitempty" xml:"return,omitempty"`
	Params []ParamInfo `json:"params,omitempty" xml:"params,omitempty"`
}

Doc api information

type ErrorFunc

type ErrorFunc func(ctx *Context, errStr string, status int)

ErrorFunc replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to ctx. The error message should be plain text.

type FileInfo

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

FileInfo implements os.FileInfo

func (*FileInfo) IsDir

func (info *FileInfo) IsDir() bool

IsDir is the abbreviation for Mode().IsDir()

func (*FileInfo) ModTime

func (info *FileInfo) ModTime() time.Time

ModTime returns modification time

func (*FileInfo) Mode

func (info *FileInfo) Mode() os.FileMode

Mode returns file mode bits

func (*FileInfo) Name

func (info *FileInfo) Name() string

Name returns base name of the file

func (*FileInfo) Size

func (info *FileInfo) Size() int64

Size returns the size in bytes for regular files; system-dependent for others

func (*FileInfo) Sys

func (info *FileInfo) Sys() interface{}

Sys returns underlying data source (can return nil)

type FileServerManager

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

FileServerManager is file cache system manager

func (*FileServerManager) FileServer

func (c *FileServerManager) FileServer(fs FileSystem) Handler

FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at fs.

To use the operating system's file system implementation, use http.Dir:

http.Handle("/", http.FileServer(http.Dir("/tmp")))

As a special case, the returned file server redirects any request ending in "/index.html" to the same path, without the final "index.html".

func (*FileServerManager) Get

func (c *FileServerManager) Get(name string) (http.File, error)

Get gets file from cache.

func (*FileServerManager) Open

func (c *FileServerManager) Open(name string, encoding string, nocache bool) (http.File, error)

Open gets or stores the file with compression and caching options. If the name is larger than 65535 or body is larger than 1/1024 of the cache size, the entry will not be written to the cache.

func (*FileServerManager) OpenFS

func (c *FileServerManager) OpenFS(ctx *Context, name string, fs FileSystem) (http.File, error)

OpenFS gets or stores the cache file. If the name is larger than 65535 or body is larger than 1/1024 of the cache size, the entry will not be written to the cache.

func (*FileServerManager) ServeContent

func (c *FileServerManager) ServeContent(ctx *Context, name string, modtime time.Time, content io.ReadSeeker)

ServeContent replies to the request using the content in the provided ReadSeeker. The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Modified-Since requests.

If the response's Content-Type header is not set, ServeContent first tries to deduce the type from name's file extension and, if that fails, falls back to reading the first block of the content and passing it to DetectContentType. The name is otherwise unused; in particular it can be empty and is never sent in the response.

If modtime is not the zero time or Unix epoch, ServeContent includes it in a Last-Modified header in the response. If the request includes an If-Modified-Since header, ServeContent uses modtime to decide whether the content needs to be sent at all.

The content's Seek method must work: ServeContent uses a seek to the end of the content to determine its size.

If the caller has set ctx's ETag header, ServeContent uses it to handle requests using If-Range and If-None-Match.

Note that *os.File implements the io.ReadSeeker interface.

func (*FileServerManager) ServeFile

func (c *FileServerManager) ServeFile(ctx *Context, name string, nocompressAndNocache ...bool)

ServeFile replies to the request with the contents of the named file or directory.

If the provided file or directory name is a relative path, it is interpreted relative to the current directory and may ascend to parent directories. If the provided name is constructed from user input, it should be sanitized before calling ServeFile. As a precaution, ServeFile will reject requests where r.URL.Path contains a ".." path element.

As a special case, ServeFile redirects any request where r.URL.Path ends in "/index.html" to the same path, without the final "index.html". To avoid such redirects either modify the path or use ServeContent.

func (*FileServerManager) Set

func (c *FileServerManager) Set(name string, body []byte, fileInfo os.FileInfo, encoding string) (http.File, error)

Set sets file to cache.

type FileSystem

type FileSystem interface {
	http.FileSystem
	Nocompress() bool // not allowed compress
	Nocache() bool    // not allowed cache
}

FileSystem is a file system with compression and caching options

func DirFS

func DirFS(root string, nocompressAndNocache ...bool) FileSystem

DirFS creates a file system with compression and caching options, similar to http.Dir

func FS

func FS(fs http.FileSystem, nocompressAndNocache ...bool) FileSystem

FS creates a file system with compression and caching options

func MarkdownFS

func MarkdownFS(root string, nocompressAndNocache ...bool) FileSystem

MarkdownFS creates a markdown file system.

func RenderFS

func RenderFS(root string, suffix string, tplVar Map) FileSystem

RenderFS creates a file system with auto-rendering. param `suffix` is used to specify the extension to be rendered, `*` for all extensions.

type Framework

type Framework struct {

	// root muxAPI node
	*MuxAPI
	// contains filtered or unexported fields
}

Framework is the faygo web framework.

func AllFrames

func AllFrames() []*Framework

AllFrames returns the list of applications that have been created.

func GetFrame

func GetFrame(name string, version ...string) (*Framework, bool)

GetFrame returns the specified frame instance by name and version.

func New

func New(name string, version ...string) *Framework

New uses the faygo web framework to create a new application.

func NewWithConfig

func NewWithConfig(config *Config, name string, version ...string) *Framework

NewWithConfig uses the faygo web framework to create a new application.

func (*Framework) CloseLog

func (frame *Framework) CloseLog()

CloseLog closes loggers.

func (*Framework) Config

func (frame *Framework) Config() Config

Config returns the framework's config copy.

func (*Framework) ConfigFilename

func (frame *Framework) ConfigFilename() string

ConfigFilename returns the framework's config file name.

func (*Framework) Filter

func (frame *Framework) Filter(fn ...HandlerFunc) *Framework

Filter operations that are called before the route is matched.

func (*Framework) Log

func (frame *Framework) Log() *logging.Logger

Log returns the logger used by the user bissness.

func (*Framework) MuxAPIsForRouter

func (frame *Framework) MuxAPIsForRouter() []*MuxAPI

MuxAPIsForRouter get an ordered list of nodes used to register router.

func (*Framework) Name

func (frame *Framework) Name() string

Name returns the name of the application

func (*Framework) NameWithVersion

func (frame *Framework) NameWithVersion() string

NameWithVersion returns the name with version

func (*Framework) NewAPI

func (frame *Framework) NewAPI(methodset Methodset, pattern string, handlers ...Handler) *MuxAPI

NewAPI creates an isolated muxAPI node.

func (*Framework) NewDELETE

func (frame *Framework) NewDELETE(pattern string, handlers ...Handler) *MuxAPI

NewDELETE is a shortcut for frame.NewAPI("DELETE", pattern, handlers...)

func (*Framework) NewGET

func (frame *Framework) NewGET(pattern string, handlers ...Handler) *MuxAPI

NewGET is a shortcut for frame.NewAPI("GET", pattern, handlers...)

func (*Framework) NewGroup

func (frame *Framework) NewGroup(pattern string, children ...*MuxAPI) *MuxAPI

NewGroup create an isolated grouping muxAPI node.

func (*Framework) NewHEAD

func (frame *Framework) NewHEAD(pattern string, handlers ...Handler) *MuxAPI

NewHEAD is a shortcut for frame.NewAPI("HEAD", pattern, handlers...)

func (*Framework) NewNamedAPI

func (frame *Framework) NewNamedAPI(name string, methodset Methodset, pattern string, handlers ...Handler) *MuxAPI

NewNamedAPI creates an isolated muxAPI node with the name.

func (*Framework) NewNamedDELETE

func (frame *Framework) NewNamedDELETE(name string, pattern string, handlers ...Handler) *MuxAPI

NewNamedDELETE is a shortcut for frame.NewNamedAPI(name, "DELETE", pattern, handlers...)

func (*Framework) NewNamedGET

func (frame *Framework) NewNamedGET(name string, pattern string, handlers ...Handler) *MuxAPI

NewNamedGET is a shortcut for frame.NewNamedAPI(name, "GET", pattern, handlers...)

func (*Framework) NewNamedGroup

func (frame *Framework) NewNamedGroup(name string, pattern string, children ...*MuxAPI) *MuxAPI

NewNamedGroup creates an isolated grouping muxAPI node with the name.

func (*Framework) NewNamedHEAD

func (frame *Framework) NewNamedHEAD(name string, pattern string, handlers ...Handler) *MuxAPI

NewNamedHEAD is a shortcut for frame.NewNamedAPI(name, "HEAD", pattern, handlers...)

func (*Framework) NewNamedOPTIONS

func (frame *Framework) NewNamedOPTIONS(name string, pattern string, handlers ...Handler) *MuxAPI

NewNamedOPTIONS is a shortcut for frame.NewNamedAPI(name, "OPTIONS", pattern, handlers...)

func (*Framework) NewNamedPATCH

func (frame *Framework) NewNamedPATCH(name string, pattern string, handlers ...Handler) *MuxAPI

NewNamedPATCH is a shortcut for frame.NewNamedAPI(name, "PATCH", pattern, handlers...)

func (*Framework) NewNamedPOST

func (frame *Framework) NewNamedPOST(name string, pattern string, handlers ...Handler) *MuxAPI

NewNamedPOST is a shortcut for frame.NewNamedAPI(name, "POST", pattern, handlers...)

func (*Framework) NewNamedPUT

func (frame *Framework) NewNamedPUT(name string, pattern string, handlers ...Handler) *MuxAPI

NewNamedPUT is a shortcut for frame.NewNamedAPI(name, "PUT", pattern, handlers...)

func (*Framework) NewNamedStatic

func (frame *Framework) NewNamedStatic(name, pattern string, root string, nocompressAndNocache ...bool) *MuxAPI

NewNamedStatic creates an isolated static muxAPI node with the name.

func (*Framework) NewNamedStaticFS

func (frame *Framework) NewNamedStaticFS(name, pattern string, fs FileSystem) *MuxAPI

NewNamedStaticFS creates an isolated static muxAPI node with the name.

func (*Framework) NewOPTIONS

func (frame *Framework) NewOPTIONS(pattern string, handlers ...Handler) *MuxAPI

NewOPTIONS is a shortcut for frame.NewAPI("OPTIONS", pattern, handlers...)

func (*Framework) NewPATCH

func (frame *Framework) NewPATCH(pattern string, handlers ...Handler) *MuxAPI

NewPATCH is a shortcut for frame.NewAPI("PATCH", pattern, handlers...)

func (*Framework) NewPOST

func (frame *Framework) NewPOST(pattern string, handlers ...Handler) *MuxAPI

NewPOST is a shortcut for frame.NewAPI("POST", pattern, handlers...)

func (*Framework) NewPUT

func (frame *Framework) NewPUT(pattern string, handlers ...Handler) *MuxAPI

NewPUT is a shortcut for frame.NewAPI("PUT", pattern, handlers...)

func (*Framework) NewStatic

func (frame *Framework) NewStatic(pattern string, root string, nocompressAndNocache ...bool) *MuxAPI

NewStatic creates an isolated static muxAPI node.

func (*Framework) NewStaticFS

func (frame *Framework) NewStaticFS(pattern string, fs FileSystem) *MuxAPI

NewStaticFS creates an isolated static muxAPI node.

func (*Framework) Route

func (frame *Framework) Route(children ...*MuxAPI) *MuxAPI

Route append middlewares of function type to root muxAPI. Used to register router in tree style.

func (*Framework) Run

func (frame *Framework) Run()

Run starts the web service.

func (*Framework) Running

func (frame *Framework) Running() bool

Running returns whether the frame service is running.

func (*Framework) ServeHTTP

func (frame *Framework) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP makes the router implement the http.Handler interface.

func (*Framework) Version

func (frame *Framework) Version() string

Version returns the version of the application

type GlobalConfig

type GlobalConfig struct {
	Cache CacheConfig `ini:"cache" comment:"Cache section"`
	Gzip  GzipConfig  `ini:"gzip" comment:"Gzip section"`
	Log   LogConfig   `ini:"log" comment:"Log section"`
	// contains filtered or unexported fields
}

GlobalConfig is global config

type GlobalVariables

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

GlobalVariables defines the global frames, configuration, function and so on.

type GzipConfig

type GzipConfig struct {
	// if EnableGzip, compress response content.
	Enable bool `ini:"enable" comment:"Whether enabled or not"`
	//Content will only be compressed if content length is either unknown or greater than gzipMinLength.
	//Default size==20B same as nginx
	MinLength int `ini:"min_length" comment:"The minimum length of content to be compressed"`
	//The compression level used for deflate compression. (0-9).
	//Non-file response Body's compression level is 0-9, but the files' always 9
	CompressLevel int `ini:"compress_level" comment:"Non-file response Body's compression level is 0-9, but the files' always 9"`
	//List of HTTP methods to compress. If not set, only GET requests are compressed.
	Methods []string `ini:"methods" delim:"|" comment:"List of HTTP methods to compress. If not set, only GET requests are compressed."`
}

GzipConfig is the config about gzip

type Handle

type Handle func(*Context, PathParams)

Handle is a function that can be registered to a route to handle HTTP requests.

type Handler

type Handler interface {
	Serve(ctx *Context) error
}

Handler is the main Faygo Handler interface.

func WrapDoc

func WrapDoc(fn HandlerFunc, note string, ret interface{}, params ...ParamInfo) Handler

WrapDoc adds a note to the handler func.

type HandlerChain

type HandlerChain []Handler

HandlerChain is the chain of handlers for a request.

type HandlerFunc

type HandlerFunc func(ctx *Context) error

HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.

func (HandlerFunc) Serve

func (h HandlerFunc) Serve(ctx *Context) error

Serve implements the Handler, is like ServeHTTP but for Faygo.

type HandlerWithBody

type HandlerWithBody interface {
	Handler
	Bodydecoder // Decode params from request body
}

HandlerWithBody is the Faygo APIHandler interface but with DecodeBody method.

type HandlerWithoutPath

type HandlerWithoutPath interface {
	Handler
}

HandlerWithoutPath is handler without binding path parameter for middleware.

type JSONMsg

type JSONMsg struct {
	Code int         `json:"code" xml:"code"`                     // the status code of the business process (required)
	Info interface{} `json:"info,omitempty" xml:"info,omitempty"` // response's schema and example value (optional)
}

JSONMsg is commonly used to return JSON format response.

type LogConfig

type LogConfig struct {
	ConsoleEnable bool   `ini:"console_enable" comment:"Whether enabled or not console logger"`
	ConsoleLevel  string `ini:"console_level" comment:"Console logger level: critical|error|warning|notice|info|debug"`
	FileEnable    bool   `ini:"file_enable" comment:"Whether enabled or not file logger"`
	FileLevel     string `ini:"file_level" comment:"File logger level: critical|error|warning|notice|info|debug"`
	AsyncLen      int    `ini:"async_len" comment:"The length of asynchronous buffer, 0 means synchronization"`
}

LogConfig is the config about log

type Map

type Map map[string]interface{}

Map is just a conversion for a map[string]interface{} should not be used inside Render when PongoEngine is used.

type Methodset

type Methodset string

Methodset is the methods string of request

func (*Methodset) Methods

func (m *Methodset) Methods() []string

Methods parses out the list of methods. List of common methods:

CONNECT
DELETE
GET
HEAD
OPTIONS
PATCH
POST
PUT
TRACE
"*"——CONNECT/DELETE/GET/HEAD/OPTIONS/PATCH/POST/PUT/TRACE

type MuxAPI

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

MuxAPI the visible api for the serveMux, in order to prepare for routing.

func (*MuxAPI) API

func (mux *MuxAPI) API(methodset Methodset, pattern string, handlers ...Handler) *MuxAPI

API adds a subordinate node to the current muxAPI grouping node. notes: handler cannot be nil.

func (*MuxAPI) Children

func (mux *MuxAPI) Children() []*MuxAPI

Children returns the children of muxAPI node.

func (*MuxAPI) DELETE

func (mux *MuxAPI) DELETE(pattern string, handlers ...Handler) *MuxAPI

DELETE is a shortcut for muxAPI.API("DELETE", pattern, handlers...)

func (*MuxAPI) Family

func (mux *MuxAPI) Family() []*MuxAPI

Family returns an ordered list of tree nodes.

func (*MuxAPI) GET

func (mux *MuxAPI) GET(pattern string, handlers ...Handler) *MuxAPI

GET is a shortcut for muxAPI.API("GET", pattern, handlers...)

func (*MuxAPI) Group

func (mux *MuxAPI) Group(pattern string, handlers ...Handler) *MuxAPI

Group adds a subordinate subgroup node to the current muxAPI grouping node. notes: handler cannot be nil.

func (*MuxAPI) HEAD

func (mux *MuxAPI) HEAD(pattern string, handlers ...Handler) *MuxAPI

HEAD is a shortcut for muxAPI.API("HEAD", pattern, handlers...)

func (*MuxAPI) HandlerProgeny

func (mux *MuxAPI) HandlerProgeny() []*MuxAPI

HandlerProgeny returns an ordered list of subordinate nodes used to register router.

func (*MuxAPI) HasMethod

func (mux *MuxAPI) HasMethod(method string) bool

HasMethod checks whether the specified method exists or not.

func (*MuxAPI) IsGroup

func (mux *MuxAPI) IsGroup() bool

IsGroup returns whether the muxapi node is group or not.

func (*MuxAPI) Methods

func (mux *MuxAPI) Methods() []string

Methods returns the methods of muxAPI node.

func (*MuxAPI) Name

func (mux *MuxAPI) Name() string

Name returns the name of muxAPI node.

func (*MuxAPI) NamedAPI

func (mux *MuxAPI) NamedAPI(name string, methodset Methodset, pattern string, handlers ...Handler) *MuxAPI

NamedAPI adds a subordinate node with the name to the current muxAPI grouping node. notes: handler cannot be nil.

func (*MuxAPI) NamedDELETE

func (mux *MuxAPI) NamedDELETE(name string, pattern string, handlers ...Handler) *MuxAPI

NamedDELETE is a shortcut for muxAPI.NamedAPI(name, "DELETE", pattern, handlers...)

func (*MuxAPI) NamedGET

func (mux *MuxAPI) NamedGET(name string, pattern string, handlers ...Handler) *MuxAPI

NamedGET is a shortcut for muxAPI.NamedAPI(name, "GET", pattern, handlers...)

func (*MuxAPI) NamedGroup

func (mux *MuxAPI) NamedGroup(name string, pattern string, handlers ...Handler) *MuxAPI

NamedGroup adds a subordinate subgroup node with the name to the current muxAPI grouping node. notes: handler cannot be nil.

func (*MuxAPI) NamedHEAD

func (mux *MuxAPI) NamedHEAD(name string, pattern string, handlers ...Handler) *MuxAPI

NamedHEAD is a shortcut for muxAPI.NamedAPI(name, "HEAD", pattern, handlers...)

func (*MuxAPI) NamedOPTIONS

func (mux *MuxAPI) NamedOPTIONS(name string, pattern string, handlers ...Handler) *MuxAPI

NamedOPTIONS is a shortcut for muxAPI.NamedAPI(name, "OPTIONS", pattern, handlers...)

func (*MuxAPI) NamedPATCH

func (mux *MuxAPI) NamedPATCH(name string, pattern string, handlers ...Handler) *MuxAPI

NamedPATCH is a shortcut for muxAPI.NamedAPI(name, "PATCH", pattern, handlers...)

func (*MuxAPI) NamedPOST

func (mux *MuxAPI) NamedPOST(name string, pattern string, handlers ...Handler) *MuxAPI

NamedPOST is a shortcut for muxAPI.NamedAPI(name, "POST", pattern, handlers...)

func (*MuxAPI) NamedPUT

func (mux *MuxAPI) NamedPUT(name string, pattern string, handlers ...Handler) *MuxAPI

NamedPUT is a shortcut for muxAPI.NamedAPI(name, "PUT", pattern, handlers...)

func (*MuxAPI) NamedStatic

func (mux *MuxAPI) NamedStatic(name, pattern string, root string, nocompressAndNocache ...bool) *MuxAPI

NamedStatic is similar to NamedStaticFS, but the second parameter is the local file path.

func (*MuxAPI) NamedStaticFS

func (mux *MuxAPI) NamedStaticFS(name, pattern string, fs FileSystem) *MuxAPI

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

frame.StaticFS("/src/*filepath", Dir("/var/www", true, true)

func (*MuxAPI) Notes

func (mux *MuxAPI) Notes() []Notes

Notes returns the notes of muxAPI node.

func (*MuxAPI) OPTIONS

func (mux *MuxAPI) OPTIONS(pattern string, handlers ...Handler) *MuxAPI

OPTIONS is a shortcut for muxAPI.API("OPTIONS", pattern, handlers...)

func (*MuxAPI) PATCH

func (mux *MuxAPI) PATCH(pattern string, handlers ...Handler) *MuxAPI

PATCH is a shortcut for muxAPI.API("PATCH", pattern, handlers...)

func (*MuxAPI) POST

func (mux *MuxAPI) POST(pattern string, handlers ...Handler) *MuxAPI

POST is a shortcut for muxAPI.API("POST", pattern, handlers...)

func (*MuxAPI) PUT

func (mux *MuxAPI) PUT(pattern string, handlers ...Handler) *MuxAPI

PUT is a shortcut for muxAPI.API("PUT", pattern, handlers...)

func (*MuxAPI) ParamInfos

func (mux *MuxAPI) ParamInfos() []ParamInfo

ParamInfos returns the paramInfos of muxAPI node.

func (*MuxAPI) Parent

func (mux *MuxAPI) Parent() *MuxAPI

Parent returns the parent of muxAPI node.

func (*MuxAPI) Path

func (mux *MuxAPI) Path() string

Path returns the path of muxAPI node.

func (*MuxAPI) Progeny

func (mux *MuxAPI) Progeny() []*MuxAPI

Progeny returns an ordered list of all subordinate nodes.

func (*MuxAPI) Static

func (mux *MuxAPI) Static(pattern string, root string, nocompressAndNocache ...bool) *MuxAPI

Static is similar to NamedStatic, but no name.

func (*MuxAPI) StaticFS

func (mux *MuxAPI) StaticFS(pattern string, fs FileSystem) *MuxAPI

StaticFS is similar to NamedStaticFS, but no name.

func (*MuxAPI) Use

func (mux *MuxAPI) Use(handlers ...Handler) *MuxAPI

Use inserts the middlewares at the left end of the node's handler chain. notes: handler cannot be nil.

type MuxAPIs

type MuxAPIs []*MuxAPI

MuxAPIs is the array of muxAPIs for sorting

func (MuxAPIs) Len

func (ends MuxAPIs) Len() int

Len returns the length of muxAPIs

func (MuxAPIs) Less

func (ends MuxAPIs) Less(i, j int) bool

Less returns the smaller muxAPI.

func (MuxAPIs) Swap

func (ends MuxAPIs) Swap(i, j int)

Swap swaps the two muxAPIs

type Notes

type Notes struct {
	Note   string      `json:"note" xml:"note"`
	Return interface{} `json:"return,omitempty" xml:"return,omitempty"`
}

Notes implementation notes of a response

type ParamInfo

type ParamInfo struct {
	Name     string      // Parameter name
	In       string      // The position of the parameter
	Required bool        // Is a required parameter
	Model    interface{} // A parameter value that is used to infer a value type and as a default value
	Desc     string      // Description
}

ParamInfo is the request parameter information

type PathParam

type PathParam struct {
	Key   string
	Value string
}

PathParam is a single URL parameter, consisting of a key and a value.

type PathParams

type PathParams []PathParam

PathParams is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func (PathParams) ByName

func (ps PathParams) ByName(name string) string

ByName returns the value of the first PathParam which key matches the given name. If no matching PathParam is found, an empty string is returned.

func (PathParams) Get

func (ps PathParams) Get(name string) (string, bool)

Get returns the value of the first PathParam which key matches the given name. It implements the apiware.KV interface.

func (PathParams) Replace

func (ps PathParams) Replace(name string, value string, n int) bool

Replace changes the value of the first PathParam which key matches the given name. If n < 0, there is no limit on the number of changed. If the key is changed, return true.

type PresetStatic

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

PresetStatic is the system default static file routing information

type Render

type Render struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Render is a custom faygo template renderer using pongo2.

func GetRender

func GetRender() *Render

GetRender returns a custom faygo template renderer using pongo2.

func (*Render) Render

func (render *Render) Render(filename string, data Map) ([]byte, error)

Render should render the template to the io.Writer.

func (*Render) RenderFromBytesWithName

func (render *Render) RenderFromBytesWithName(filename string, fbytes []byte, data Map) ([]byte, error)

RenderFromBytesWithName should render the template to the io.Writer.

func (*Render) TemplateVar

func (render *Render) TemplateVar(name string, v interface{})

TemplateVar sets the global template variable or function

type Response

type Response struct {
	// 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 http.ResponseWriter(https://golang.org/pkg/net/http/#ResponseWriter)

func (*Response) AddCookie

func (resp *Response) AddCookie(cookie *http.Cookie)

AddCookie adds a Set-Cookie header. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func (*Response) CloseNotify

func (resp *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.

func (*Response) Committed

func (resp *Response) Committed() bool

Committed returns whether the response has been submitted or not.

func (*Response) DelCookie

func (resp *Response) DelCookie()

DelCookie sets Set-Cookie header.

func (*Response) Flush

func (resp *Response) Flush()

Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client.

func (*Response) Header

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

Header returns the header map 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.

func (*Response) Hijack

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

Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection.

func (*Response) ReadFrom

func (resp *Response) ReadFrom(src io.Reader) (int64, error)

ReadFrom is here to optimize copying from an *os.File regular file to a *net.TCPConn with sendfile.

func (*Response) SetCookie

func (resp *Response) SetCookie(cookie *http.Cookie)

SetCookie sets a Set-Cookie header.

func (*Response) Size

func (resp *Response) Size() int64

Size returns the current size, in bytes, of the response.

func (*Response) Status

func (resp *Response) Status() int

Status returns the HTTP status code of the response.

func (*Response) Write

func (resp *Response) Write(b []byte) (int, error)

Write writes the data to the connection as part of an HTTP reply. If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data. If the Header does not contain a Content-Type line, Write adds a Content-Type set to the result of passing the initial 512 bytes of written data to DetectContentType.

func (*Response) WriteHeader

func (resp *Response) WriteHeader(status 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 RouterConfig

type RouterConfig struct {
	// Enables automatic redirection if the current route can't be matched but a
	// handler for the path with (without) the trailing slash exists.
	// For example if /foo/ is requested but a route only exists for /foo, the
	// client is redirected to /foo with http status code 301 for GET requests
	// and 307 for all other request methods.
	RedirectTrailingSlash bool `ini:"redirect_trailing_slash" comment:"Automatic redirection (for example, '/foo/' -> '/foo')"`
	// If enabled, the router tries to fix the current request path, if no
	// handle is registered for it.
	// First superfluous path elements like ../ or // are removed.
	// Afterwards the router does a case-insensitive lookup of the cleaned path.
	// If a handle can be found for this route, the router makes a redirection
	// to the corrected path with status code 301 for GET requests and 307 for
	// all other request methods.
	// For example /FOO and /..//Foo could be redirected to /foo.
	// RedirectTrailingSlash is independent of this option.
	RedirectFixedPath bool `ini:"redirect_fixed_path" comment:"Tries to fix the current request path, if no handle is registered for it"`
	// If enabled, the router checks if another method is allowed for the
	// current route, if the current request can not be routed.
	// If this is the case, the request is answered with 'Method Not Allowed'
	// and HTTP status code 405.
	// If no other Method is allowed, the request is delegated to the NotFound
	// handler.
	HandleMethodNotAllowed bool `ini:"handle_method_not_allowed" comment:"Returns 405 if the requested method does not exist, otherwise returns 404"`
	// If enabled, the router automatically replies to OPTIONS requests.
	// Custom OPTIONS handlers take priority over automatic replies.
	HandleOPTIONS bool `ini:"handle_options" comment:"Automatic response OPTIONS request, you can set the default Handler in faygo"`
	DefaultUpload bool `ini:"default_upload" comment:"Automatically register the default router: /upload/*filepath"`
	DefaultStatic bool `ini:"default_static" comment:"Automatically register the default router: /static/*filepath"`
}

RouterConfig is the config about router

type SavedFileInfo

type SavedFileInfo struct {
	Url  string
	Size int64
}

SavedFileInfo for SaveFiles()

type Server

type Server struct {
	*http.Server
	// contains filtered or unexported fields
}

Server web server object

type SessionConfig

type SessionConfig struct {
	Enable                bool   `ini:"enable" comment:"Whether enabled or not"`
	Provider              string `ini:"provider" comment:"Data storage"`
	Name                  string `ini:"name" comment:"The client stores the name of the cookie"`
	ProviderConfig        string `ini:"provider_config" comment:"According to the different engine settings different config information"`
	CookieLifeSecond      int    `ini:"cookie_life_second" comment:"The default value is 0, which is the lifetime of the browser"`
	GcLifeSecond          int64  `ini:"gc_life_second" comment:"The interval between triggering the GC"`
	MaxLifeSecond         int64  `ini:"max_life_second" comment:"The session max lefetime"`
	AutoSetCookie         bool   `ini:"auto_setcookie" comment:"Automatically set on the session cookie value, the general default true"`
	Domain                string `ini:"domain" comment:"The domain name that is allowed to access this cookie"`
	EnableSidInHttpHeader bool   `ini:"enable_sid_in_header" comment:"Whether to write a session ID to the header"`
	NameInHttpHeader      string `ini:"name_in_header" comment:"The name of the header when the session ID is written to the header"`
	EnableSidInUrlQuery   bool   `ini:"enable_sid_in_urlquery" comment:"Whether to write the session ID to the URL Query params"`
}

SessionConfig is the config about session

type Tpl

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

Tpl is template with modfied time.

type XSRFConfig

type XSRFConfig struct {
	Enable       bool   `ini:"enable" comment:"Whether enabled or not"`
	Key          string `ini:"key" comment:"Encryption key"`
	ExpireSecond int    `ini:"expire_second" comment:"Expire of XSRF token"`
}

XSRFConfig is the config about XSRF filter

Directories

Path Synopsis
Package apiware provides a tools which can bind the http/fasthttp request params to the structure and validate.
Package apiware provides a tools which can bind the http/fasthttp request params to the structure and validate.
ext
barcode/codabar
Package codabar can create Codabar barcodes
Package codabar can create Codabar barcodes
barcode/code128
Package code128 can create Code128 barcodes
Package code128 can create Code128 barcodes
barcode/code39
Package code39 can create Code39 barcodes
Package code39 can create Code39 barcodes
barcode/datamatrix
Package datamatrix can create Datamatrix barcodes
Package datamatrix can create Datamatrix barcodes
barcode/ean
Package ean can create EAN 8 and EAN 13 barcodes.
Package ean can create EAN 8 and EAN 13 barcodes.
barcode/qr
Package qr can be used to create QR barcodes.
Package qr can be used to create QR barcodes.
barcode/twooffive
Package twooffive can create interleaved and standard "2 of 5" barcodes.
Package twooffive can create interleaved and standard "2 of 5" barcodes.
barcode/utils
Package utils contain some utilities which are needed to create barcodes
Package utils contain some utilities which are needed to create barcodes
cron
Package cron implements a cron spec parser and job runner.
Package cron implements a cron spec parser and job runner.
db/directsql
* * desc : 参数校验函数 * author : 畅雨 * date : 2016.12.13 * desc : * history : 2017.05.28 - 增加主从表关联id的服务端处理。
* * desc : 参数校验函数 * author : 畅雨 * date : 2016.12.13 * desc : * history : 2017.05.28 - 增加主从表关联id的服务端处理。
otp
Package otp implements both HOTP and TOTP based one time passcodes in a Google Authenticator compatible manner.
Package otp implements both HOTP and TOTP based one time passcodes in a Google Authenticator compatible manner.
surfer
import ( "github.com/henrylee2cn/surfer" "io/ioutil" "log" ) func main() { // Use surf engine resp, err := surfer.Download(&surfer.Request{ Url: "http://github.com/henrylee2cn/surfer", }) if err != nil { log.Fatal(err) } b, err := ioutil.ReadAll(resp.Body) log.Println(string(b), err) // Use phantomjs engine resp, err = surfer.Download(&surfer.Request{ Url: "http://github.com/henrylee2cn", DownloaderID: 1, }) if err != nil { log.Fatal(err) } b, err = ioutil.ReadAll(resp.Body) log.Println(string(b), err) resp.Body.Close() surfer.DestroyJsFiles() }
import ( "github.com/henrylee2cn/surfer" "io/ioutil" "log" ) func main() { // Use surf engine resp, err := surfer.Download(&surfer.Request{ Url: "http://github.com/henrylee2cn/surfer", }) if err != nil { log.Fatal(err) } b, err := ioutil.ReadAll(resp.Body) log.Println(string(b), err) // Use phantomjs engine resp, err = surfer.Download(&surfer.Request{ Url: "http://github.com/henrylee2cn", DownloaderID: 1, }) if err != nil { log.Fatal(err) } b, err = ioutil.ReadAll(resp.Body) log.Println(string(b), err) resp.Body.Close() surfer.DestroyJsFiles() }
uuid
Package uuid generates and inspects UUIDs.
Package uuid generates and inspects UUIDs.
websocket
Package websocket implements the WebSocket protocol defined in RFC 6455.
Package websocket implements the WebSocket protocol defined in RFC 6455.
websocket/examples/autobahn
Command server is a test server for the Autobahn WebSockets Test Suite.
Command server is a test server for the Autobahn WebSockets Test Suite.
murmur3
Native (and fast) implementation of Austin Appleby's MurmurHash3.
Native (and fast) implementation of Austin Appleby's MurmurHash3.
server
A basic freecache server supports redis protocol
A basic freecache server supports redis protocol
Package gracenet provides a family of Listen functions that either open a fresh connection or provide an inherited connection from when the process was started.
Package gracenet provides a family of Listen functions that either open a fresh connection or provide an inherited connection from when the process was started.
Package logging implements a logging infrastructure for Go.
Package logging implements a logging infrastructure for Go.
Blackfriday markdown processor.
Blackfriday markdown processor.
A Django-syntax like template-engine Blog posts about pongo2 (including introduction and migration): https://www.florian-schlachter.de/?tag=pongo2 Complete documentation on the template language: https://docs.djangoproject.com/en/dev/topics/templates/ Try out pongo2 live in the pongo2 playground: https://www.florian-schlachter.de/pongo2/ Make sure to read README.md in the repository as well.
A Django-syntax like template-engine Blog posts about pongo2 (including introduction and migration): https://www.florian-schlachter.de/?tag=pongo2 Complete documentation on the template language: https://docs.djangoproject.com/en/dev/topics/templates/ Try out pongo2 live in the pongo2 playground: https://www.florian-schlachter.de/pongo2/ Make sure to read README.md in the repository as well.
samples
directsql/common
功能:pongo2模板数据库访问函数 日期:2017.01.06
功能:pongo2模板数据库访问函数 日期:2017.01.06
directsql/router
* * desc : 系统功能路由注册 * author:畅雨 * date: 2016.05.16 * history: *
* * desc : 系统功能路由注册 * author:畅雨 * date: 2016.05.16 * history: *
Package session provider Usage: import( "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "cookieLifeTime": 3600, "providerConfig": ""}`) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md modify: henrylee
Package session provider Usage: import( "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "enableSetCookie,omitempty": true, "gclifetime":3600, "maxLifetime": 3600, "secure": false, "cookieLifeTime": 3600, "providerConfig": ""}`) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md modify: henrylee
couchbase
Package couchbase for session provider depend on github.com/couchbaselabs/go-couchbasee go install github.com/couchbaselabs/go-couchbase Usage: import( _ "github.com/astaxie/beego/session/couchbase" "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("couchbase", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"http://host:port/, Pool, Bucket"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
Package couchbase for session provider depend on github.com/couchbaselabs/go-couchbasee go install github.com/couchbaselabs/go-couchbase Usage: import( _ "github.com/astaxie/beego/session/couchbase" "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("couchbase", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"http://host:port/, Pool, Bucket"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
ledis
Package ledis provide session Provider
Package ledis provide session Provider
memcache
Package memcache for session provider depend on github.com/bradfitz/gomemcache/memcache go install github.com/bradfitz/gomemcache/memcache Usage: import( _ "github.com/astaxie/beego/session/memcache" "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("memcache", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:11211"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
Package memcache for session provider depend on github.com/bradfitz/gomemcache/memcache go install github.com/bradfitz/gomemcache/memcache Usage: import( _ "github.com/astaxie/beego/session/memcache" "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("memcache", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:11211"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
mysql
Package mysql for session provider depends on github.com/go-sql-driver/mysql: go install github.com/go-sql-driver/mysql mysql session support need create table as sql: CREATE TABLE `session` ( `session_key` char(64) NOT NULL, `session_data` blob, `session_expiry` int(11) unsigned NOT NULL, PRIMARY KEY (`session_key`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; Usage: import( _ "github.com/astaxie/beego/session/mysql" "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("mysql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
Package mysql for session provider depends on github.com/go-sql-driver/mysql: go install github.com/go-sql-driver/mysql mysql session support need create table as sql: CREATE TABLE `session` ( `session_key` char(64) NOT NULL, `session_data` blob, `session_expiry` int(11) unsigned NOT NULL, PRIMARY KEY (`session_key`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; Usage: import( _ "github.com/astaxie/beego/session/mysql" "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("mysql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
postgres
Package postgres for session provider depends on github.com/lib/pq: go install github.com/lib/pq needs this table in your database: CREATE TABLE session ( session_key char(64) NOT NULL, session_data bytea, session_expiry timestamp NOT NULL, CONSTRAINT session_key PRIMARY KEY(session_key) ); will be activated with these settings in app.conf: SessionOn = true SessionProvider = postgresql SessionSavePath = "user=a password=b dbname=c sslmode=disable" SessionName = session Usage: import( _ "github.com/astaxie/beego/session/postgresql" "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("postgresql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"user=pqgotest dbname=pqgotest sslmode=verify-full"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
Package postgres for session provider depends on github.com/lib/pq: go install github.com/lib/pq needs this table in your database: CREATE TABLE session ( session_key char(64) NOT NULL, session_data bytea, session_expiry timestamp NOT NULL, CONSTRAINT session_key PRIMARY KEY(session_key) ); will be activated with these settings in app.conf: SessionOn = true SessionProvider = postgresql SessionSavePath = "user=a password=b dbname=c sslmode=disable" SessionName = session Usage: import( _ "github.com/astaxie/beego/session/postgresql" "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("postgresql", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"user=pqgotest dbname=pqgotest sslmode=verify-full"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
redis
Package redis for session provider depend on github.com/garyburd/redigo/redis go install github.com/garyburd/redigo/redis Usage: import( _ "github.com/astaxie/beego/session/redis" "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("redis", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
Package redis for session provider depend on github.com/garyburd/redigo/redis go install github.com/garyburd/redigo/redis Usage: import( _ "github.com/astaxie/beego/session/redis" "github.com/astaxie/beego/session" ) func init() { globalSessions, _ = session.NewManager("redis", “{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"127.0.0.1:7070"}“) go globalSessions.GC() } more docs: http://beego.me/docs/module/session.md
Package swagger struct definition
Package swagger struct definition

Jump to

Keyboard shortcuts

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