gone是可以高效开发Web服务的Golang依赖注入框架
github地址:https://github.com/gone-io/gone
文档地址:https://goner.fun/zh/
使用goner/gin
提供Web服务
文章目录
注册相关的Goners
这里我们编写一个Priest
函数,用于注册相关的Goners。
package main
import (
"github.com/gone-io/gone"
"github.com/gone-io/gone/goner"
)
// 用于注册Goners的Priest函数
func Priest(cemetery gone.Cemetery) error {
//注册gin相关的Goners
_ = goner.GinPriest(cemetery)
//TODO: 注册其他的Goners
return nil
}
func main() {
// 在main函数中使用Priest函数启动服务
gone.Serve(Priest)
}
将上面代码保存为main.go
,,代码已经能够正常运行起来了,运行中代码会监听本地8080
端口,但是所有的请求都是返回404。
编写Controller挂载路由
为了提供服务,而不只是返回404,我们需要编写一个Controller,挂载路由。
新建文件controller.go
,编写如下代码:
// NewController controller 的构造函数
func NewController() gone.Goner {
return &controller{
}
}
type controller struct {
gone.Flag
root gone.RouteGroup `gone:"*"` // 根路由组
}
func (ctr *controller) Mount() gone.GinMountError {
ctr.root.GET("/ping", func() string {
return "hello gone"
})
return nil
}
然后,在main.go
文件Priest
函数中添加注册Controller
的代码: