faygo: github.com/henrylee2cn/faygo Index | Files | Directories

package faygo

import "github.com/henrylee2cn/faygo"

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

Package Files

apidoc.go config.go context.go context_input.go context_output.go doc.go faygo.go framework.go fs.go graceful_b.go handler.go helper.go log.go mime.go muxapi.go render_pongo2.go response_writer.go server.go tree.go

Constants

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

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

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

const FilepathKey = "filepath"

FilepathKey path key for static router pattern.

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

)

some default config

const MinShutdownTimeout = 5 * time.Second

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

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

Variables

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

var BytesToString = goutil.BytesToString

BytesToString convert []byte type to string type.

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

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

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

FileExists reports whether the named file or directory exists.

func FileExists(name string) bool
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)
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
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)
var ObjectName = goutil.ObjectName

ObjectName gets the type name of the object

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

RESTfulMethodList is the list of all RESTful methods

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
var RelPath = goutil.RelPath

RelPath gets relative path.

func RelPath() string
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)
var SelfChdir = goutil.SelfChdir

SelfChdir switch the working path to my own path.

func SelfChdir()
var SelfDir = goutil.SelfDir

SelfDir gets compiled executable file directory

func SelfDir() string
var SelfPath = goutil.SelfPath

SelfPath gets compiled executable file absolute path.

func SelfPath() string
var SnakeString = goutil.SnakeString

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

func SnakeString(s string) string
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
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)

func CleanToURL Uses

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 Uses

func CloseLog()

CloseLog closes global loggers.

func ConfigDir Uses

func ConfigDir() string

ConfigDir returns the config files directory

func ContentTypeByExtension Uses

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 Uses

func Critical(args ...interface{})

Critical logs a message using CRITICAL as log level.

func Criticalf Uses

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

Criticalf logs a message using CRITICAL as log level.

func Debug Uses

func Debug(args ...interface{})

Debug logs a message using DEBUG as log level.

func Debugf Uses

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

Debugf logs a message using DEBUG as log level.

func DecodeBody Uses

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

DecodeBody decodes params from request body.

func Error Uses

func Error(args ...interface{})

Error logs a message using ERROR as log level.

func Errorf Uses

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

Errorf logs a message using ERROR as log level.

func Fatal Uses

func Fatal(args ...interface{})

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

func Fatalf Uses

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

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

func HandleBinderror Uses

func HandleBinderror(ctx *Context, err error)

HandleBinderror calls the default parameter binding failure handler.

func HandleError Uses

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

HandleError calls the default error handler.

func Info Uses

func Info(args ...interface{})

Info logs a message using INFO as log level.

func Infof Uses

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

Infof logs a message using INFO as log level.

func IsHandlerWithoutPath Uses

func IsHandlerWithoutPath(handler Handler, noDefaultParams bool) bool

IsHandlerWithoutPath verifies that the Handler is an HandlerWithoutPath.

func JoinStatic Uses

func JoinStatic(shortFilename string) string

JoinStatic adds the static directory prefix to the file name.

func LogDir Uses

func LogDir() string

LogDir returns logs folder path with a slash at the end

func MapParamName Uses

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 Uses

func NewLog() *logging.Logger

NewLog gets a global logger

func Notice Uses

func Notice(args ...interface{})

Notice logs a message using NOTICE as log level.

func Noticef Uses

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

Noticef logs a message using NOTICE as log level.

func Panic Uses

func Panic(args ...interface{})

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

func Panicf Uses

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

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

func Print Uses

func Print(args ...interface{})

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

func Printf Uses

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

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

func Reboot Uses

func Reboot(timeout ...time.Duration)

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

func RemoveUseless Uses

func RemoveUseless()

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

func RenderVar Uses

func RenderVar(name string, v interface{})

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

func Run Uses

func Run()

Run starts all web services.

func Running Uses

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

Running returns whether the frame service is running.

func SetBinderrorFunc Uses

func SetBinderrorFunc(binderrorFunc BinderrorFunc)

SetBinderrorFunc sets the global default `BinderrorFunc` function.

func SetBodydecoder Uses

func SetBodydecoder(bodydecoder apiware.Bodydecoder)

SetBodydecoder sets the global default `Bodydecoder` function.

func SetErrorFunc Uses

func SetErrorFunc(errorFunc ErrorFunc)

SetErrorFunc sets the global default `ErrorFunc` function.

func SetParamNameMapper Uses

func SetParamNameMapper(paramNameMapper apiware.ParamNameMapper)

SetParamNameMapper sets the global default `ParamNameMapper` function.

func SetShutdown Uses

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 Uses

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 Uses

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 Uses

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 Uses

func StaticDir() string

StaticDir returns static folder path with a slash at the end

func SyncINI Uses

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 Uses

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

ToAPIHandler tries converts it to an *apiHandler.

func UploadDir Uses

func UploadDir() string

UploadDir returns upload folder path with a slash at the end

func Warning Uses

func Warning(args ...interface{})

Warning logs a message using WARNING as log level.

func Warningf Uses

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

Warningf logs a message using WARNING as log level.

func WritePid Uses

func WritePid(pidFilename string) error

WritePid write pid to the specified file.

type APIDoc Uses

type APIDoc interface {
    Doc() Doc
}

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

type APIHandler Uses

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 Uses

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 `ini:"whitelist" delim:"|" comment:"'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       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 Uses

func (conf *APIdocConfig) Comb()

Comb combs APIdoc config

type BinderrorFunc Uses

type BinderrorFunc func(ctx *Context, err error)

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

type Bodydecoder Uses

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

Bodydecoder is an interface to customize decoding operation

type CacheConfig Uses

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 Uses

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

CacheFile implements os.File

func NewFile Uses

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

NewFile creates a cacheFile

func (*CacheFile) Close Uses

func (c *CacheFile) Close() error

Close closes file

func (*CacheFile) Readdir Uses

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

Readdir gets path info

func (*CacheFile) Stat Uses

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

Stat returns file info

type Config Uses

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 `ini:"slow_response_threshold" comment:"When response time > slow_response_threshold, log level = 'WARNING'; 0 means not limited; ns|µs|ms|s|m|h"`

    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 Uses

func NewDefaultConfig() *Config

NewDefaultConfig creates a new default framework config.

type Context Uses

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 Uses

func (ctx *Context) AcceptHTML() bool

AcceptHTML Checks if request accepts html response

func (*Context) AcceptJSON Uses

func (ctx *Context) AcceptJSON() bool

AcceptJSON Checks if request accepts json response

func (*Context) AcceptXML Uses

func (ctx *Context) AcceptXML() bool

AcceptXML Checks if request accepts xml response

func (*Context) BindBizParam Uses

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 Uses

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

BindForm reads form data from request's body

func (*Context) BindJSON Uses

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

BindJSON reads JSON from request's body

func (*Context) BindXML Uses

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

BindXML reads XML from request's body

func (*Context) BizParam Uses

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 Uses

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 Uses

func (ctx *Context) Committed() bool

Committed returns whether the response has been submitted or not.

func (*Context) CookieParam Uses

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 Uses

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

Data returns the stored data in this context.

func (*Context) DataAll Uses

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

DataAll return the implicit data in the context

func (*Context) Del Uses

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

Del delete data by key.

func (*Context) DelSession Uses

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

DelSession removes value from session.

func (*Context) DestroySession Uses

func (ctx *Context) DestroySession()

DestroySession cleans session data and session cookie.

func (*Context) Domain Uses

func (ctx *Context) Domain() string

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

func (*Context) Error Uses

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

Send error message and stop handler chain.

func (*Context) File Uses

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

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

func (*Context) FormFile Uses

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 Uses

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 Uses

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

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

func (*Context) FormParams Uses

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

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

func (*Context) GetSession Uses

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

GetSession gets value from session.

func (*Context) HTML Uses

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

HTML sends an HTTP response with status code.

func (*Context) HasData Uses

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

HasData checks if the key exists in the context.

func (*Context) HasFormFile Uses

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

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

func (*Context) HeaderParam Uses

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 Uses

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

HeaderParamAll returns the whole ruest header.

func (*Context) Host Uses

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 Uses

func (ctx *Context) IP() string

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

func (*Context) Is Uses

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

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

func (*Context) IsAjax Uses

func (ctx *Context) IsAjax() bool

IsAjax returns boolean of this request is generated by ajax.

func (*Context) IsBreak Uses

func (ctx *Context) IsBreak() bool

IsBreak returns whether the operation is stopped halfway.

func (*Context) IsCachable Uses

func (ctx *Context) IsCachable() bool

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

func (*Context) IsClientError Uses

func (ctx *Context) IsClientError() bool

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

func (*Context) IsDelete Uses

func (ctx *Context) IsDelete() bool

IsDelete Is this a DELETE method request?

func (*Context) IsEmpty Uses

func (ctx *Context) IsEmpty() bool

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

func (*Context) IsForbidden Uses

func (ctx *Context) IsForbidden() bool

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

func (*Context) IsGet Uses

func (ctx *Context) IsGet() bool

IsGet Is this a GET method request?

func (*Context) IsHead Uses

func (ctx *Context) IsHead() bool

IsHead Is this a Head method request?

func (*Context) IsNotFound Uses

func (ctx *Context) IsNotFound() bool

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

func (*Context) IsOk Uses

func (ctx *Context) IsOk() bool

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

func (*Context) IsOptions Uses

func (ctx *Context) IsOptions() bool

IsOptions Is this a OPTIONS method request?

func (*Context) IsPatch Uses

func (ctx *Context) IsPatch() bool

IsPatch Is this a PATCH method request?

func (*Context) IsPost Uses

func (ctx *Context) IsPost() bool

IsPost Is this a POST method request?

func (*Context) IsPut Uses

func (ctx *Context) IsPut() bool

IsPut Is this a PUT method request?

func (*Context) IsRedirect Uses

func (ctx *Context) IsRedirect() bool

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

func (*Context) IsSecure Uses

func (ctx *Context) IsSecure() bool

IsSecure returns boolean of this request is in https.

func (*Context) IsServerError Uses

func (ctx *Context) IsServerError() bool

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

func (*Context) IsSuccessful Uses

func (ctx *Context) IsSuccessful() bool

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

func (*Context) IsUpload Uses

func (ctx *Context) IsUpload() bool

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

func (*Context) IsWebsocket Uses

func (ctx *Context) IsWebsocket() bool

IsWebsocket returns boolean of this request is in webSocket.

func (*Context) JSON Uses

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

JSON sends a JSON response with status code.

func (*Context) JSONBlob Uses

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

JSONBlob sends a JSON blob response with status code.

func (*Context) JSONMsg Uses

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

JSONMsg sends a JSON with JSONMsg format.

func (*Context) JSONOrXML Uses

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 Uses

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 Uses

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 Uses

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

Log used by the user bissness

func (*Context) Method Uses

func (ctx *Context) Method() string

Method returns http request method.

func (*Context) ModifyPath Uses

func (ctx *Context) ModifyPath(p string)

ModifyPath modifies the access path for the request.

func (*Context) Next Uses

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 Uses

func (ctx *Context) NoContent(status int)

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

func (*Context) Param Uses

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 Uses

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

ParseFormOrMulitForm parseForm or parseMultiForm based on Content-type

func (*Context) Path Uses

func (ctx *Context) Path() string

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

func (*Context) PathParam Uses

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

PathParam returns path param by key.

func (*Context) PathParamAll Uses

func (ctx *Context) PathParamAll() PathParams

PathParamAll returns whole path parameters.

func (*Context) Port Uses

func (ctx *Context) Port() int

Port returns the port number of request.

func (*Context) Protocol Uses

func (ctx *Context) Protocol() string

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

func (*Context) Proxy Uses

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

Proxy returns proxy client ips slice.

func (*Context) QueryParam Uses

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 Uses

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

QueryParamAll returns all query params.

func (*Context) QueryParams Uses

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

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

func (*Context) RealIP Uses

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 Uses

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 Uses

func (ctx *Context) Referer() string

Referer returns http referer header.

func (*Context) Render Uses

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 Uses

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 Uses

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 Uses

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 Uses

func (ctx *Context) Scheme() string

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

func (*Context) SecureCookieParam Uses

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

SecureCookieParam Get secure cookie from request by a given key.

func (*Context) SessionRegenerateID Uses

func (ctx *Context) SessionRegenerateID()

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

func (*Context) SetCookie Uses

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 Uses

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 Uses

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

SetHeader sets response header item string via given key.

func (*Context) SetSecureCookie Uses

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

SetSecureCookie Set Secure cookie for response.

func (*Context) SetSession Uses

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

SetSession puts value into session.

func (*Context) Site Uses

func (ctx *Context) Site() string

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

func (*Context) Size Uses

func (ctx *Context) Size() int64

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

func (*Context) Status Uses

func (ctx *Context) Status() int

Status returns the HTTP status code of the response.

func (*Context) Stop Uses

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 Uses

func (ctx *Context) Stopped() bool

Stopped returns whether the operation has stopped.

func (*Context) String Uses

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 Uses

func (ctx *Context) URI() string

URI returns full request url with query string, fragment.

func (*Context) URL Uses

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

URL returns full request url with query string, fragment.

func (*Context) UserAgent Uses

func (ctx *Context) UserAgent() string

UserAgent returns request client user agent string.

func (*Context) XML Uses

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

XML sends an XML response with status code.

func (*Context) XMLBlob Uses

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

XMLBlob sends a XML blob response with status code.

func (*Context) XSRFFormHTML Uses

func (ctx *Context) XSRFFormHTML() string

XSRFFormHTML writes an input field contains xsrf token value.

func (*Context) XSRFToken Uses

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 Uses

type Doc struct {
    Note   string      `json:"note" xml:"note"`
    Return interface{} `json:"return,omitempty" xml:"return,omitempty"`
    // MoreParams extra added parameters definition
    MoreParams []ParamInfo `json:"more_params,omitempty" xml:"more_params,omitempty"`
}

Doc api information

type ErrorFunc Uses

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 Uses

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

FileInfo implements os.FileInfo

func (*FileInfo) IsDir Uses

func (info *FileInfo) IsDir() bool

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

func (*FileInfo) ModTime Uses

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

ModTime returns modification time

func (*FileInfo) Mode Uses

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

Mode returns file mode bits

func (*FileInfo) Name Uses

func (info *FileInfo) Name() string

Name returns base name of the file

func (*FileInfo) Size Uses

func (info *FileInfo) Size() int64

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

func (*FileInfo) Sys Uses

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

Sys returns underlying data source (can return nil)

type FileServerManager Uses

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

FileServerManager is file cache system manager

func (*FileServerManager) FileServer Uses

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 Uses

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

Get gets file from cache.

func (*FileServerManager) Open Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

Set sets file to cache.

type FileSystem Uses

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 Uses

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

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

func FS Uses

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

FS creates a file system with compression and caching options

func MarkdownFS Uses

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

MarkdownFS creates a markdown file system.

func RenderFS Uses

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 Uses

type Framework struct {

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

Framework is the faygo web framework.

func AllFrames Uses

func AllFrames() []*Framework

AllFrames returns the list of applications that have been created.

func GetFrame Uses

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

GetFrame returns the specified frame instance by name and version.

func New Uses

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

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

func NewWithConfig Uses

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

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

func (*Framework) CloseLog Uses

func (frame *Framework) CloseLog()

CloseLog closes loggers.

func (*Framework) Config Uses

func (frame *Framework) Config() Config

Config returns the framework's config copy.

func (*Framework) ConfigFilename Uses

func (frame *Framework) ConfigFilename() string

ConfigFilename returns the framework's config file name.

func (*Framework) Filter Uses

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

Filter operations that are called before the route is matched.

func (*Framework) Log Uses

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

Log returns the logger used by the user bissness.

func (*Framework) MuxAPIsForRouter Uses

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

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

func (*Framework) Name Uses

func (frame *Framework) Name() string

Name returns the name of the application

func (*Framework) NameWithVersion Uses

func (frame *Framework) NameWithVersion() string

NameWithVersion returns the name with version

func (*Framework) NewAPI Uses

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

NewAPI creates an isolated muxAPI node.

func (*Framework) NewDELETE Uses

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

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

func (*Framework) NewGET Uses

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

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

func (*Framework) NewGroup Uses

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

NewGroup create an isolated grouping muxAPI node.

func (*Framework) NewHEAD Uses

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

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

func (*Framework) NewNamedAPI Uses

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 Uses

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 Uses

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 Uses

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

NewNamedGroup creates an isolated grouping muxAPI node with the name.

func (*Framework) NewNamedHEAD Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

NewNamedStaticFS creates an isolated static muxAPI node with the name.

func (*Framework) NewOPTIONS Uses

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

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

func (*Framework) NewPATCH Uses

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

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

func (*Framework) NewPOST Uses

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

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

func (*Framework) NewPUT Uses

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

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

func (*Framework) NewStatic Uses

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

NewStatic creates an isolated static muxAPI node.

func (*Framework) NewStaticFS Uses

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

NewStaticFS creates an isolated static muxAPI node.

func (*Framework) Route Uses

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 Uses

func (frame *Framework) Run()

Run starts the web service.

func (*Framework) Running Uses

func (frame *Framework) Running() bool

Running returns whether the frame service is running.

func (*Framework) ServeHTTP Uses

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

ServeHTTP makes the router implement the http.Handler interface.

func (*Framework) Version Uses

func (frame *Framework) Version() string

Version returns the version of the application

type GlobalConfig Uses

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 Uses

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

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

type GzipConfig Uses

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 Uses

type Handle func(*Context, PathParams)

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

type Handler Uses

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

Handler is the main Faygo Handler interface.

func WrapDoc Uses

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

WrapDoc adds a note to the handler func.

type HandlerChain Uses

type HandlerChain []Handler

HandlerChain is the chain of handlers for a request.

type HandlerFunc Uses

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 Uses

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

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

type HandlerWithBody Uses

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

HandlerWithBody is the Faygo APIHandler interface but with DecodeBody method.

type HandlerWithoutPath Uses

type HandlerWithoutPath interface {
    Handler
}

HandlerWithoutPath is handler without binding path parameter for middleware.

type JSONMsg Uses

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 Uses

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 Uses

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 Uses

type Methodset string

Methodset is the methods string of request

func (*Methodset) Methods Uses

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 Uses

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

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

func (*MuxAPI) API Uses

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 Uses

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

Children returns the children of muxAPI node.

func (*MuxAPI) DELETE Uses

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

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

func (*MuxAPI) Family Uses

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

Family returns an ordered list of tree nodes.

func (*MuxAPI) GET Uses

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

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

func (*MuxAPI) Group Uses

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 Uses

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

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

func (*MuxAPI) HandlerProgeny Uses

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

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

func (*MuxAPI) HasMethod Uses

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

HasMethod checks whether the specified method exists or not.

func (*MuxAPI) IsGroup Uses

func (mux *MuxAPI) IsGroup() bool

IsGroup returns whether the muxapi node is group or not.

func (*MuxAPI) Methods Uses

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

Methods returns the methods of muxAPI node.

func (*MuxAPI) Name Uses

func (mux *MuxAPI) Name() string

Name returns the name of muxAPI node.

func (*MuxAPI) NamedAPI Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

Notes returns the notes of muxAPI node.

func (*MuxAPI) OPTIONS Uses

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

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

func (*MuxAPI) PATCH Uses

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

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

func (*MuxAPI) POST Uses

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

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

func (*MuxAPI) PUT Uses

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

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

func (*MuxAPI) ParamInfos Uses

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

ParamInfos returns the paramInfos of muxAPI node.

func (*MuxAPI) Parent Uses

func (mux *MuxAPI) Parent() *MuxAPI

Parent returns the parent of muxAPI node.

func (*MuxAPI) Path Uses

func (mux *MuxAPI) Path() string

Path returns the path of muxAPI node.

func (*MuxAPI) Progeny Uses

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

Progeny returns an ordered list of all subordinate nodes.

func (*MuxAPI) Static Uses

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

Static is similar to NamedStatic, but no name.

func (*MuxAPI) StaticFS Uses

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

StaticFS is similar to NamedStaticFS, but no name.

func (*MuxAPI) Use Uses

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 Uses

type MuxAPIs []*MuxAPI

MuxAPIs is the array of muxAPIs for sorting

func (MuxAPIs) Len Uses

func (ends MuxAPIs) Len() int

Len returns the length of muxAPIs

func (MuxAPIs) Less Uses

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

Less returns the smaller muxAPI.

func (MuxAPIs) Swap Uses

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

Swap swaps the two muxAPIs

type Notes Uses

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 Uses

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 Uses

type PathParam struct {
    Key   string
    Value string
}

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

type PathParams Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

PresetStatic is the system default static file routing information

type Render Uses

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

Render is a custom faygo template renderer using pongo2.

func GetRender Uses

func GetRender() *Render

GetRender returns a custom faygo template renderer using pongo2.

func (*Render) Render Uses

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

Render should render the template to the io.Writer.

func (*Render) RenderFromBytesWithName Uses

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

RenderFromBytesWithName should render the template to the io.Writer.

func (*Render) TemplateVar Uses

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

TemplateVar sets the global template variable or function

type Response Uses

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 Uses

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 Uses

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 Uses

func (resp *Response) Committed() bool

Committed returns whether the response has been submitted or not.

func (*Response) DelCookie Uses

func (resp *Response) DelCookie()

DelCookie sets Set-Cookie header.

func (*Response) Flush Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

SetCookie sets a Set-Cookie header.

func (*Response) Size Uses

func (resp *Response) Size() int64

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

func (*Response) Status Uses

func (resp *Response) Status() int

Status returns the HTTP status code of the response.

func (*Response) Write Uses

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 Uses

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 Uses

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"`
    NoDefaultParams bool `ini:"no_default_params" comment:"If true, don't assign default request parameter values based on initial parameter values of the routing handler"`
    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 Uses

type SavedFileInfo struct {
    Url  string
    Size int64
}

SavedFileInfo for SaveFiles()

type Server Uses

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

Server web server object

type SessionConfig Uses

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 Uses

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

Tpl is template with modfied time.

type XSRFConfig Uses

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

PathSynopsis
acceptencoder
apiwarePackage apiware provides a tools which can bind the http/fasthttp request params to the structure and validate.
ext/barcode
ext/barcode/codabarPackage codabar can create Codabar barcodes
ext/barcode/code128Package code128 can create Code128 barcodes
ext/barcode/code39Package code39 can create Code39 barcodes
ext/barcode/datamatrixPackage datamatrix can create Datamatrix barcodes
ext/barcode/eanPackage ean can create EAN 8 and EAN 13 barcodes.
ext/barcode/qrPackage qr can be used to create QR barcodes.
ext/barcode/twooffivePackage twooffive can create interleaved and standard "2 of 5" barcodes.
ext/barcode/utilsPackage utils contain some utilities which are needed to create barcodes
ext/bitconv
ext/cronPackage cron implements a cron spec parser and job runner.
ext/db/directsql
ext/db/directsqlx
ext/db/gorm
ext/db/sqlx
ext/db/xorm
ext/middleware
ext/middleware/jwt
ext/middleware/jwt/sample
ext/otpPackage otp implements both HOTP and TOTP based one time passcodes in a Google Authenticator compatible manner.
ext/otp/example
ext/otp/hotp
ext/otp/totp
ext/surferimport ( "github.com/henrylee2cn/surfer" "io/ioutil" "log" )
ext/surfer/example
ext/task
ext/uuidPackage uuid generates and inspects UUIDs.
ext/websocketPackage websocket implements the WebSocket protocol defined in RFC 6455.
ext/websocket/examples/autobahnCommand server is a test server for the Autobahn WebSockets Test Suite.
ext/websocket/examples/chat
ext/websocket/examples/command
ext/websocket/examples/filewatch
freecache
freecache/murmur3Native (and fast) implementation of Austin Appleby's MurmurHash3.
freecache/serverA basic freecache server supports redis protocol
gracenetPackage gracenet provides a family of Listen functions that either open a fresh connection or provide an inherited connection from when the process was started.
loggingPackage logging implements a logging infrastructure for Go.
logging/color
logging/examples
markdownBlackfriday markdown processor.
pongo2A Django-syntax like template-engine
samples/demo
samples/demo/clienttest
samples/demo/handler
samples/demo/middleware
samples/demo/router
samples/directsql
samples/directsql/common功能:pongo2模板数据库访问函数 日期:2017.01.06
samples/directsql/handler
samples/directsql/router
samples/directsqlx
samples/directsqlx/common功能:pongo2模板数据库访问函数 日期:2017.01.06
samples/directsqlx/handler
samples/directsqlx/router
samples/MultiUsage
samples/myconfig
sessionPackage session provider
session/couchbasePackage couchbase for session provider
session/ledisPackage ledis provide session Provider
session/memcachePackage memcache for session provider
session/mysqlPackage mysql for session provider
session/postgresPackage postgres for session provider
session/redisPackage redis for session provider
session/ssdb
swaggerPackage swagger struct definition
_syso

Package faygo imports 55 packages (graph) and is imported by 69 packages. Updated 2020-08-08. Refresh now. Tools for package owners.