Faygo a Go Web framework that's best for developing APIs

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Faygo Frame

Using the new architecture, Faygo is the most appropriate go web framework for developing API interfaces. By simply defining a struct Handler, users can automatically bind, validate request parameters, and generate online API documentation.

Faygo Project Source Code

View the User Guide

Official QQ Group: Go-web Programming 42730308


Faygo Index
Faygo Apidoc
Faygo Server

Installation Requirements

Go version≥1.8

Quick to use

    • Mode One source download
go get -u -v github.com/henrylee2cn/faygo
    • Mode II Deployment Tool (Go to Fay)
go get -u -v github.com/henrylee2cn/fay
        fay command [arguments]The commands are:        new        创建、编译和运行(监控文件变化)一个新的faygo项目        run        编译和运行(监控文件变化)任意一个已存在的golang项目fay new appname [apptpl]        appname    指定新faygo项目的创建目录        apptpl     指定一个faygo项目模板(可选)fay run [appname]        appname    指定待运行的golang项目路径(可选)

Frame Properties

    • One struct Handler more thing to do:

      • Define Handler/middleware
      • binding and Validating Request parameters
      • Generate Swagger2.0 API online documentation
      • Database ORM Mapping
    • Handler and middleware are exactly the same, are implemented handler interface ( func or struct type), together constitute a route operation chain, but the conceptual level of the statement is different

    • Supports multiple network types:
Network type configuration net_types value
HT TP http
https/http2 (TLS) HTTPS
HTTPS/HTTP2 (let ' s Encrypt TLS) letsencrypt
HTTPS/HTTP2 (Let's Encrypt TLS on UNIX sockets) unix_letsencrypt
HTTP (UNIX socket) unix_http
HTTPS/HTTP2 (TLS on UNIX sockets) unix_https
    • Support single-service single-monitor, single-service multi-monitor, multi-service multi-monitor, etc., the configuration information of multiple services is independent of each other
    • httproutersupport for flexible static file routing (e.g. Dirfs, renderfs, MARKDOWNFS, etc.) based on the development of high-performance routing, supporting both chained and tree registration styles
    • Supports smooth shutdown, smooth upgrade, provides Fay tools for new projects, hot compilation, meta-programming
    • Use the most powerful pongo2 as an HTML rendering engine
    • Provides approximate LRU file caching capabilities, primarily for static file caching
    • Cross-platform color log system with support for both console and file two output formats (can be used simultaneously)
    • provides session management functions
    • Supports gzip global configuration
    • Provides XSRF cross-site request forgery security filtering
    • Most features use a compact INI configuration as much as possible to avoid unnecessary recompilation, and these profiles support auto-filling default values
    • Provide,,,,, and gorm xorm sqlx directSQL Websocket ini http client Many other common expansion packs

Faygo struct Handler multi-purpose unity

Simple example

Package Mainimport (//"Mime/multipart" "Time" "Github.com/henrylee2cn/faygo") type Index struct {Id i NT ' param: "<in:path> <required> <desc:ID> <range:0:10>" ' Title string ' param: "<i  n: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 (+, 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=xyzresponse: {"Id": 1, "Ti Tle ":" Test "," Paragraph ": [" abc "," XYZ "]," Cookie ":" 2016-11-13 01:14:40.903 8005 +0800 CST "}*/

Sample Library

Operations and middleware

Operation and middleware are the same, are implemented handler interface!

    • function type
// 不含API文档描述func Page() faygo.HandlerFunc {    return func(ctx *faygo.Context) error {        return ctx.String(200, "faygo")    }}// 含API文档描述var Page2 = faygo.WrapDoc(Page(), "测试页2的注意事项", "文本")
    • struct type
// Param操作通过Tag绑定并验证请求参数type Param struct {    Id    int    `param:"<in:path> <required> <desc:ID> <range: 0:10>"`    Title string `param:"<in:query>"`}// Serve实现Handler接口func (p *Param) Serve(ctx *faygo.Context) error {    return ctx.JSON(200,        faygo.Map{            "Struct Params":    p,            "Additional Param": ctx.PathParam("additional"),        }, true)}// Doc实现API文档接口(可选)func (p *Param) Doc() faygo.Doc {    return faygo.Doc{        // 向API文档声明接口注意事项        Note: "param desc",        // 向API文档声明响应内容格式        Return: faygo.JSONMsg{            Code: 1,            Info: "success",        },        // 向API文档增加额外的请求参数声明(可选)        Params: []faygo.ParamInfo{            {                Name:  "additional",                In:    "path",                Model: "a",                Desc:  "defined by the `Doc()` method",            },        },    }}

Filter function

The filter function must be of type Handlerfunc!

func Root2Index(ctx *faygo.Context) error {    // 不允许直接访问`/index`    if ctx.Path() == "/index" {        ctx.Stop()        return nil    }    if ctx.Path() == "/" {        ctx.ModifyPath("/index")    }    return nil}

Route Registration

    • Tree-shaped
// 新建应用服务,参数:名称、版本var app1 = faygo.New("myapp1", "1.0")// 路由app1.Filter(Root2Index).    Route(        app1.NewNamedGET("测试页1", "/page", Page()),        app1.NewNamedGET("测试页2", "/page2", Page2),        app1.NewGroup("home",            app1.NewNamedGET("test param", "/param", &Param{                // 为绑定的参数设定API文档中缺省值(可选)                Id:    1,                Title: "test param",            }),        ),    )
    • Chain-like
// 新建应用服务,参数:名称、版本var app2 = faygo.New("myapp2", "1.0")// 路由app2.Filter(Root2Index)app2.NamedGET("test page", "/page", Page())app2.NamedGET("test page2", "/page2", Page2)app2.Group("home"){    app2.NamedGET("test param", "/param", &Param{        // 为绑定的参数设定API文档中缺省值(可选)        Id:    1,        Title: "test param",    })}

Smooth shutdown and restart

    • Smooth Close
kill [pid]
    • Smooth restart
kill -USR2 [pid]

Expansion pack

Expansion Pack Import Path
Various barcode github.com/henrylee2cn/faygo/ext/barcode
Bit units github.com/henrylee2cn/faygo/ext/bitconv
Gorm Database Engine github.com/henrylee2cn/faygo/ext/db/gorm
SQLX Database Engine github.com/henrylee2cn/faygo/ext/db/sqlx
Xorm Database Engine github.com/henrylee2cn/faygo/ext/db/xorm
Directsql (Configure SQL Engine) github.com/henrylee2cn/faygo/ext/db/directsql
Password algorithm github.com/henrylee2cn/faygo/ext/otp
Uuid github.com/henrylee2cn/faygo/ext/uuid
Websocket github.com/henrylee2cn/faygo/ext/websocket
INI configuration github.com/henrylee2cn/faygo/ini
Timer github.com/henrylee2cn/faygo/ext/cron
Task Tools github.com/henrylee2cn/faygo/ext/task
HTTP Client github.com/henrylee2cn/faygo/ext/surfer

Open Source Agreement

The Faygo project is published in a commercial application-friendly Apache2.0 protocol.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.