代码拉取完成,页面将自动刷新
Go-Air是一个基于 net/http 包实现的极简Http路由库,旨在提供简洁易用、原生一致的HTTP路由功能。
GoAir不打算提供传统Web框架大而全的工具库,GoAir的目标是为物联网领域,尤其在边缘计算上,提供一个性能优秀、节省内存的API Web开发环境。
GET
/POST
/DELETE
/PUT
/OPTIONS
/HEAD
方法的注册API;全局Middleware
中间件;作用域Middleware
中间件;/users/:userid
;/users/:id{[0-9]+}
;Install:
go get github.com/yoojia/go-air
Demo:
func main() {
srv := air.New()
// 全局Middleware
srv.Use(func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Server", "Air v0.0.1")
next.ServeHTTP(w, req)
}
})
srv.GET("/hello",
// Handler
func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("World"))
},
// 当前Handler作用域的Middleware
func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Scoped", "Hello here")
next.ServeHTTP(w, r)
}
})
// 路径动态参数,从 axle.Vars 中获取
srv.GET("/say/:word", func(w http.ResponseWriter, req *http.Request) {
vars := axle.Vars(req)
word := vars["word"]
w.Write([]byte(word))
})
// Post
srv.POST("/hi", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("HI~~"))
})
srv.Start(":9090")
}
在与对比测试中详见benchmark,GoAir有极好的路由性能表现;
HttpRouter干不过,真是太快了。我不喜欢它的一点是Handler不是原生http.HandleFunc
,而是自定义加上params。
包括echo等在内的GoWeb框架,我都不喜欢;它们都实现一套自己的Handler,这种深度绑定某个框架会让我非常纠结,而我只需要一个简单的API路由而已。
测试环境:
单API性能对比
名称 | 性能数据 |
---|---|
HttpRouter | 86 ns/op |
Alex | 396 ns/op |
Mux | 2052 ns/op |
GithubAPI性能对比
Router注册Github API数量:203
名称 | 性能数据 |
---|---|
HttpRouter | 229 ns/op |
Alex | 1170 ns/op |
Mux | 35057 ns/op |
原始测试数据:
goos: linux
goarch: amd64
pkg: github.com/yoojia/go-axle/benchmark
BenchmarkSimpleGoAir-4 3000000 396 ns/op
BenchmarkSimpleMux-4 1000000 2052 ns/op
BenchmarkSimpleHttpRouter-4 20000000 86.4 ns/op
BenchmarkGithubApiGoAir-4 1000000 1170 ns/op
BenchmarkGithubApiMux-4 50000 35057 ns/op
BenchmarkGithubHttpRouter-4 10000000 229 ns/op
PASS
Copyright (c) 2019 Yoojia Chen yoojiachen@gmail.com
Under MIT, see: LICENSE
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。