1 Star 0 Fork 80

deeokay / faygo

forked from andeyalee / faygo 
Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
Clone or Download
contribute
Sync branch
Cancel
Notice: Creating folder will generate an empty file .keep, because not support in Git
Loading...
README
Apache-2.0

Faygo report card github issues github closed issues GitHub release GoDoc

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.1

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

  • 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

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2016 HenryLee 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.

About

Faygo 是一款快速、简洁的Go Web框架,可用极少的代码开发出高性能的Web应用程序(尤其是API接口)。只需定义 struct Handler,Faygo 就能自动绑定、验证请求参数并生成在线API文档。 expand collapse
Go
Apache-2.0
Cancel

Releases

No release

Contributors

All

Activities

Load More
can not load any more
Go
1
https://gitee.com/MoneyDee/faygo.git
git@gitee.com:MoneyDee/faygo.git
MoneyDee
faygo
faygo
master

Search