Gear 是 Go 语言下的一个轻量级、可组合、高性能的 Web 服务框架

网友投稿 708 2022-11-05

Gear 是 Go 语言下的一个轻量级、可组合、高性能的 Web 服务框架

Gear 是 Go 语言下的一个轻量级、可组合、高性能的 Web 服务框架

A lightweight, composable and high performance web service framework for Go.

Features

Effective and flexible middlewares flow control, create anything by middlewarePowerful and smart HTTP error handlingTrie base gear.Router, as faster as HttpRouter, support regexp parameters and group routesIntegrated timeout context.ContextIntegrated response content compressIntegrated structured logging middlewareIntegrated request body parserIntegrated signed cookiesIntegrated JSON, JSONP, XML and HTML rendererIntegrated CORS, Secure, Favicon and Static middlewaresMore useful methods on gear.Context to manipulate HTTP Request/ResponseRun HTTP and gRPC on the same portCompletely HTTP/2.0 supported

Documentation

Go-Documentation

Import

// package gearimport "github.com/teambition/gear"

Design

Server 底层基于原生 net/http 而不是 fasthttp通过 gear.Middleware 中间件模式扩展功能模块中间件的单向顺序流程控制和级联流程控制功能强大,完美集成 context.Context 的 gear.Context集中、智能、可自定义的错误和异常处理After Hook 和 End Hook 的后置处理Any interface 无限的 gear.Context 状态扩展能力请求数据的解析和验证

FAQ

如何从源码自动生成 Swagger v2 的文档?Go 语言完整的应用项目结构最佳实践是怎样的?

Demo

Hello

https://github.com/teambition/gear/tree/master/example/hello

app := gear.New() // Add logging middleware app.UseHandler(logging.Default(true)) // Add router middleware router := gear.NewRouter() // try: http://127.0.0.1:3000/hello router.Get("/hello", func(ctx *gear.Context) error { return ctx.HTML(200, "

Hello, Gear!

") }) // try: http://127.0.0.1:3000/test?query=hello router.Otherwise(func(ctx *gear.Context) error { return ctx.JSON(200, map[string]interface{}{ "Host": ctx.Host, "Method": ctx.Method, "Path": ctx.Path, "URI": ctx.Req.RequestURI, "Headers": ctx.Req.Header, }) }) app.UseHandler(router) app.Error(app.Listen(":3000"))

HTTP2 with Push

https://github.com/teambition/gear/tree/master/example/http2

package mainimport ( "net/http" "github.com/teambition/gear" "github.com/teambition/gear/logging" "github.com/teambition/gear/middleware/favicon")// go run example/http2/app.go// Visit: https://127.0.0.1:3000/func main() { const htmlBody = `

Hello, Gear!

` const pushBody = `h1 { color: red;}` app := gear.New() app.UseHandler(logging.Default(true)) app.Use(favicon.New("./testdata/favicon.ico")) router := gear.NewRouter() router.Get("/", func(ctx *gear.Context) error { ctx.Res.Push("/hello.css", &http.PushOptions{Method: "GET"}) return ctx.HTML(200, htmlBody) }) router.Get("/hello.css", func(ctx *gear.Context) error { ctx.Type("text/css") return ctx.End(200, []byte(pushBody)) }) app.UseHandler(router) app.Error(app.ListenTLS(":3000", "./testdata/out/test.crt", "./testdata/out/test.key"))}

A CMD tool: static server

https://github.com/teambition/gear/tree/master/example/staticgo

Install it with go:

go install github.com/teambition/gear/example/staticgo

It is a useful CMD tool that serve your local files as web server (support TLS). You can build osx, linux, windows version with make build.

package mainimport ( "flag" "github.com/teambition/gear" "github.com/teambition/gear/logging" "github.com/teambition/gear/middleware/cors" "github.com/teambition/gear/middleware/static")var ( address = flag.String("addr", "127.0.0.1:3000", `address to listen on.`) path = flag.String("path", "./", `static files path to serve.`) certFile = flag.String("certFile", "", `certFile path, used to create TLS static server.`) keyFile = flag.String("keyFile", "", `keyFile path, used to create TLS static server.`))func main() { flag.Parse() app := gear.New() app.UseHandler(logging.Default(true)) app.Use(cors.New()) app.Use(static.New(static.Options{Root: *path})) logging.Println("staticgo v1.1.0, created by https://github.com/teambition/gear") logging.Printf("listen: %s, serve: %s\n", *address, *path) if *certFile != "" && *keyFile != "" { app.Error(app.ListenTLS(*address, *certFile, *keyFile)) } else { app.Error(app.Listen(*address)) }}

HTTP2 & gRPC

https://github.com/teambition/gear/tree/master/example/grpc_server

https://github.com/teambition/gear/tree/master/example/grpc_client

About Router

gear.Router is a trie base HTTP request handler. Features:

Support named parameterSupport regexpSupport suffix matchingSupport multi-routerSupport router layer middlewaresSupport fixed path automatic redirectionSupport trailing slash automatic redirectionAutomatic handle 405 Method Not AllowedAutomatic handle OPTIONS methodBest Performance

The registered path, against which the router matches incoming requests, can contain six types of parameters:

SyntaxDescription
:namenamed parameter
:name(regexp)named with regexp parameter
:name+suffixnamed parameter with suffix matching
:name(regexp)+suffixnamed with regexp parameter and suffix matching
:name*named with catch-all parameter
::namenot named parameter, it is literal :name

Named parameters are dynamic path segments. They match anything until the next '/' or the path end:

Defined: /api/:type/:ID

/api/user/123 matched: type="user", ID="123"/api/user no match/api/user/123/comments no match

Named with regexp parameters match anything using regexp until the next '/' or the path end:

Defined: /api/:type/:ID(^\d+$)

/api/user/123 matched: type="user", ID="123"/api/user no match/api/user/abc no match/api/user/123/comments no match

Named parameters with suffix, such as Google API Design:

Defined: /api/:resource/:ID+:undelete

/api/file/123 no match/api/file/123:undelete matched: resource="file", ID="123"/api/file/123:undelete/comments no match

Named with regexp parameters and suffix:

Defined: /api/:resource/:ID(^\d+$)+:cancel

/api/task/123 no match/api/task/123:cancel matched: resource="task", ID="123"/api/task/abc:cancel no match

Named with catch-all parameters match anything until the path end, including the directory index (the '/' before the catch-all). Since they match anything until the end, catch-all parameters must always be the final path element.

Defined: /files/:filepath*

/files no match/files/LICENSE matched: filepath="LICENSE"/files/templates/article.html matched: filepath="templates/article.html"

The value of parameters is saved on the Matched.Params. Retrieve the value of a parameter by name:

type := matched.Params("type")id := matched.Params("ID")

More Middlewares

Structured logging: github.com/teambition/gear/loggingCORS handler: github.com/teambition/gear/middleware/corsSecure handler: github.com/teambition/gear/middleware/secureStatic serving: github.com/teambition/gear/middleware/staticFavicon serving: github.com/teambition/gear/middleware/favicongRPC serving: github.com/teambition/gear/middleware/grpcJWT and Crypto auth: Gear-AuthCookie session: Gear-SessionSession middleware: https://github.com/go-session/gear-sessionSmart rate limiter: Gear-RatelimiterCSRF: Gear-CSRFOpentracing with Zipkin: Gear-Tracing

License

Gear is licensed under the MIT license. Copyright © 2016-2020 Teambition.

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

上一篇:一篇文章带你了解常用的Maven命令
下一篇:mybatis返回map结果集@MapKey使用的场景分析
相关文章

 发表评论

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