您现在的位置是:首页 > 文章详情

go-mir v1.0.2 发布,用 Go 结构体标签定义 handler 路由信息的辅助库

日期:2019-11-13点击:524

go-mir v1.0.2 发布了,推荐使用。

小版本更新

  • 主要更新依赖包

预告下一版本开发计划

前段时间忙于公司业务,go-mir断更了好长时间,现在有闲余时间,正在筹划着go-mir的升级。

go-mir v1的架构大体是这样:

go-mir-v1-arc

这套架构主要是使用了golang的反射机制对struct tag解析然后注册路由信息到web engine,只影响启动时间,不会有运行时损耗,总体来说,方便了接口定义,对代码组织很有益处。

go-mir v2版本正在筹划中,已经开始敲代码了,大体架构如下:

go-mir-v2-arc

v2版本将升级采用代码生成的方式生成接口代码,同样也是采用golang内置的struct tag定义路由信息,但不同于v1版本在引擎启动时解析后注册路由信息到web引擎,这里参考grpc的接口生成方式,生成接口定义文件,业务逻辑只要实现了接口,注册接口实现的对象到相应的web引擎,启动后就可以对外通过RESTfull接口获取服务。

go-mir v3版本将会直接使用OpenAPI v3定义接口,大体架构如下:

go-mir-v3-arc

v3版本将使用OpenApi v3.0的定义文件直接生成接口代码,后面的逻辑和v2保持一致。使用OpenAPI v3.0定义RESTfull API接口非常清晰、方便的,一直都想从OpenApi 的定义文件直接生成golang接口文件,go-mir v3版本将提供这个特性的支持,敬请期待。

使用go-mir构建web服务的样例代码

go-mir 是一个使用 golang 结构体标签信息将方法注册为 http engine handler 的辅助库,目前支持将方法注册到 GinEchoIrisMacaronMuxhttproutergo-chi

主要功能:

  • 使用 go 结构体标签定义 handler 的路由信息用于注册

  • 通过反射机制根据结构体标签信息获取结构体方法,并依据结构体标签信息注册到相应的 http engine 中,比如 GinEchoIrisMacaronMuxhttproutergo-chi

  • 使用结构体方法编写 http handler

  • 使用结构体标签定义 Middleware 信息,并注册到 http engine 中

代码示例:(eg: gin backend)

  • Get Mir.Gin module first

 go get github.com/alimy/mir/module/gin@master
  • Then happy in codding enjoy your heart...

 package main import(     "github.com/alimy/mir"     "github.com/gin-gonic/gin"     "net/http"          mirE "github.com/alimy/mir/module/gin" ) type site struct {     Chain mir.Chain     `mir:"-"`     Group mir.Group     `mir:"v1"`     index mir.Get       `mir:"/index/"`     articles mir.Get    `mir:"/articles/:category/#GetArticles"` } // Index handler of the index field that in site struct, the struct tag indicate // this handler will register to path "/index/" and method is http.MethodGet. func (h *site) Index(c *gin.Context) {     c.String(http.StatusOK, "get index data") } // GetArticles handler of articles indicator that contains Host/Path/Queries/Handler info. // Path info is the second or first(if no host info) segment start with '/'(eg: /articles/:category/#GetArticles) // Handler info is forth info start with '#' that indicate real handler method name(eg: GetArticles).if no handler info will // use field name capital first char as default handler name(eg: if articles had no #GetArticles then the handler name will // is Articles)  func (h *site) GetArticles(c *gin.Context) {     c.String(http.StatusOK, "get articles data") } func main() {     //Create a new gin engine     engine := gin.New()          // Register handler to engine by mir     mirE.Register(engine, &site{Chain: gin.HandlersChain{gin.Logger()}})          // Start gin engine serve     engine.Run() }
原文链接:https://www.oschina.net/news/111297/go-mir-1-0-2-released
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章