Faygo 使用全新架构,是最合适开发API接口的Go Web框架

网友投稿 932 2022-10-26

Faygo 使用全新架构,是最合适开发API接口的Go Web框架

Faygo 使用全新架构,是最合适开发API接口的Go Web框架

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

简体中文

Latest version

Version

v1.2.0

Requirements

Go Version ≥ 1.8

Quick Start

Way 1: download source

go get -u -v github.com/henrylee2cn/faygo

Way 2: deployment tools (Go to fay)

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 projectfay new appname [apptpl] appname specifies the path of the new faygo project apptpl optionally, specifies the faygo project template typefay run [appname] appname optionally, specifies the path of the new project

Features

One struct Handler can get more things:

Define Handler/MiddlewareBind and verify request parametersGenerate an online document for the Swagger 2.0 APIDatabase 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 typesConfiguration net_types
HTTPhttp
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 otherThe 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 functionUse the most powerful pongo2 as the HTML rendering engineSupport 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 (If you use a persistent storage engine, you must use gob.Register() to register the relevant custom type before starting the service)Support global gzip compression configSupport XSRF security filteringMost features try to use simple ini configs to avoid unnecessary recompilation, and these profiles can be automatically assigned default valuesProvide gorm, xorm, sqlx, directSQL, Websocket, ini, http client and many other commonly used expansion packages

Simple example

package mainimport ( // "mime/multipart" "time" "github.com/henrylee2cn/faygo")type Index struct { Id int `param:" "` Title string `param:" "` Paragraph []string `param:" "` Cookie string `param:" "` // Picture *multipart.FileHeader `param:" "`}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=xyzresponse: { "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 descriptionfunc Page() faygo.HandlerFunc { return func(ctx *faygo.Context) error { return ctx.String(200, "faygo") }}// Page2 handler contains API doc descriptionvar Page2 = faygo.WrapDoc(Page(), "test page2 notes", "test")

struct type

// Param binds and validates the request parameters by Tagstype Param struct { Id int `param:" "` Title string `param:""`}// Serve implemente Handler interfacefunc (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, versionvar app1 = faygo.New("myapp1", "1.0")// routerapp1.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, versionvar app2 = faygo.New("myapp2", "1.0")// routerapp2.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_letsencryptaddrs = 0.0.0.0:80|0.0.0.0:443 # List of multiple listening addressestls_certfile = # TLS certificate file pathtls_keyfile = # TLS key file pathletsencrypt_dir = # Let's Encrypt TLS certificate cache directoryunix_filemode = 0666 # File permissions for UNIX listener, requires octal numberhttp_redirect_https = false # Redirect from 'http://hostname:port1' to 'https://hostname:port2'read_timeout = 0s # Maximum duration for reading the full; ns|µs|ms|s|m|h request (including body)write_timeout = 0s # Maximum duration for writing the full; ns|µs|ms|s|m|h response (including body)multipart_maxmemory_mb = 32 # Maximum size of memory that can be used when receiving uploaded filesslow_response_threshold= 0s # When response time > slow_response_threshold, log level = 'WARNING'; 0 means not limited; ns|µs|ms|s|m|hprint_body = false # Form requests are printed in JSON format, but other types are printed as-is[router] # Routing config sectionredirect_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 ithandle_method_not_allowed = true # Returns 405 if the requested method does not exist, otherwise returns 404handle_options = true # Automatic response OPTIONS request, you can set the default Handler in Faygono_default_params = false # If true, don't assign default request parameter values based on initial parameter values of the routing handlerdefault_upload = true # Automatically register the default router: /upload/*filepathdefault_static = true # Automatically register the default router: /static/*filepath[xsrf] # XSRF security sectionenable = false # Whether enabled or notkey = faygoxsrf # Encryption keyexpire_second = 3600 # Expire of XSRF token[session] # Session sectionenable = false # Whether enabled or notprovider = memory # Data storagename = faygosessionID # The client stores the name of the cookieprovider_config = # According to the different engine settings different config informationcookie_life_second = 0 # The default value is 0, which is the lifetime of the browsergc_life_second = 300 # The interval between triggering the GCmax_life_second = 3600 # The session max lefetimeauto_setcookie = true # Automatically set on the session cookie value, the general default truedomain = # The domain name that is allowed to access this cookieenable_sid_in_header = false # Whether to write a session ID to the headername_in_header = Faygosessionid # The name of the header when the session ID is written to the headerenable_sid_in_urlquery = false # Whether to write the session ID to the URL Query params[apidoc] # API documentation sectionenable = true # Whether enabled or notpath = /apidoc # The URL pathnolimit = false # If true, access is not restrictedreal_ip = false # If true, means verifying the real IP of the visitorwhitelist = 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 alloweddesc = # Description of the applicationemail = # Technician's Emailterms_url = # Terms of servicelicense = # The license used by the APIlicense_url = # The URL of the protocol content page

Only one global config is applied (config/__global__.ini). Refer to the following:

[cache] # Cache sectionenable = false # Whether enabled or notsize_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 sectionenable = false # Whether enabled or notmin_length = 20 # The minimum length of content to be compressedcompress_level = 1 # Non-file response Body's compression level is 0-9, but the files' always 9methods = GET # List of HTTP methods to compress. If not set, only GET requests are compressed.[log] # Log sectionconsole_enable = true # Whether enabled or not console loggerconsole_level = debug # Console logger level: critical | error | warning | notice | info | debugfile_enable = true # Whether enabled or not file loggerfile_level = debug # File logger level: critical | error | warning | notice | info | debugasync_len = 0 # The length of asynchronous buffer, 0 means synchronization

Handler struct tags

tagkeyrequiredvaluedesc
paraminonly onepath(position of param) if required is unsetted, auto set it. e.g. url: "http://abc.com/a/{path}"
paraminonly onequery(position of param) e.g. url: "http://abc.com/a?b={query}"
paraminonly oneformData(position of param) e.g. "request body: a=123&b={formData}"
paraminonly onebody(position of param) request body can be any content
paraminonly oneheader(position of param) request header info
paraminonly onecookie(position of param) request cookie info, support: *http.Cookie,http.Cookie,string,[]byte
paramnameno(e.g.id)specify request param`s name
paramrequirednorequest param is required
paramdescno(e.g.id)request param description
paramlenno(e.g.3:6)length range [a,b] of param's value
paramrangeno(e.g.0:10)numerical range [a,b] of param's value
paramnonzeronoparam`s value can not be zero
parammaxmbno(e.g.32)when request Content-Type is multipart/form-data, the max memory for body.(multi-param, whichever is greater)
paramregexpno(e.g.^\\w+$)verify the value of the param with a regular expression(param value can not be null)
paramerrno(e.g.incorrect password format)the custom error for binding or validating

NOTES:

the binding object must be a struct pointerin addition to *multipart.FileHeader, the binding struct's field can not be a pointerif the param tag is not exist, anonymous field will be parsedwhen 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 uploadedif param's position(in) is cookie, field's type must be *http.Cookie or http.Cookieparam tags in(formData) and in(body) can not exist at the same timethere should not be more than one in(body) param tag

Handler struct fields type

baseslicespecial
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[]int8http.Cookie (only for net/http's cookie param)
int16[]int16struct (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 summaryimport path
barcodegithub.com/henrylee2cn/faygo/ext/barcode
Bit unit conversiongithub.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 Passwordgithub.com/henrylee2cn/faygo/ext/otp
UUIDgithub.com/henrylee2cn/faygo/ext/uuid
Websocketgithub.com/henrylee2cn/faygo/ext/websocket
inigithub.com/henrylee2cn/faygo/ini
crongithub.com/henrylee2cn/faygo/ext/cron
taskgithub.com/henrylee2cn/faygo/ext/task
http clientgithub.com/henrylee2cn/faygo/ext/surfer

Know Cases

Product NameWeb/App ServerHome Page
盯房Apphttps://df-house.com
eTradeApphttps://fir.im/ejy
OneForApphttps://fir.im/eqb
杰运好车Apphttps://itunes.apple.com/cn/app/%E6%9D%B0%E8%BF%90%E5%A5%BD%E8%BD%A6/id1301132479?mt=8

Note: Sorted in alphabetical order

Business Users

License

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:js-------字符串去重之利用对象的属性不能重复去重
下一篇:JS-----------关于new一个对象
相关文章

 发表评论

暂时没有评论,来抢沙发吧~