gin自动路由中间件

chenqinghe · 2020-01-13 11:01:54 · 1873 次点击    
这是一个分享于 2020-01-13 11:01:54 的资源,其中的信息可能已经有所发展或是发生改变。

gin-autorouter

gin-autorouter is a middleware which could automatic mapping request url to a handler method.

Api

the project have two main functions:

  • AutoRouter
  • RouterAny

Basic Uage

package main


type T struct{

}

func (t *T)Greet(c *gin.Context)  {
    c.Writer.WriteString("hello from *T.Greet")
}

func (t *T)Hello(c *gin.Context) {
    c.Writer.WriteString("hello from *T.Hello")
}


func main(){
    r:=gin.Default()
    r.Any("/*path",router.AutoRouter(&T{}))
    r.Run(":8080")    
}

you only need to register a router with pattern "/*path"

view http://localhost:8080/greet, you could see "hello from *T.Greet"

view http://localhost:8080/hello, you will see "hello from *T.Hello"

RESTful Api

with AutoRouter, you can create restful api very easily.

package main

func (h *Article) Get(c *gin.Context) {
    articleId := c.Param("id")
    // search artile stuff.....
    article := model.SearchArticle(articleId)
    c.JSONP(http.StatusOK,article)
}

func (h *Article)Delete(c *gin.Context) {
    articleId := c.Param("id")
    model.DeleteArticle(articleId)
    c.JSONP(http.StatusOK,"ok")
}

func main(){
    r := gin.Default()
    r.Any("/article/:id",router.AutoRouter(&Article{}))
}

//  * GET /article/123 => *Article.Get
//  * Delete /article/123 => *Article.Delete

also, you can use RouterAny, things will be extremely easy!!

package main

func (h *Article)Get(c *gin.Context, id int) {
    fmt.Println("article:",id) // output: article: 123
    article := model.SearchArticle(id)
    c.JSONP(http.StatusOK,article)
}

func (h *Article)Delete(c *gin.Context, id int) {
    fmt.Println("article:",id) // output: article: 123
    model.DeleteArticle(id)
    c.JSONP(http.StatusOK,"ok")
}


func main(){
    r:= gin.Default()
    r.Any("/*path",router.RouterAny(&Article{}))
}

// GET /article/123 => *Article.Get(c, 123)
// DELETE /article/123 => *Article.Delete(c, 123)

Mapping Rules

the mapping is basic on *gin.Context.Param("path"). path will be exploded to several segments by '/'

  • if path is empty, method is request http method
  • the first segment is method
  • others will be method arguments
  • segments number MUST be equal or greater than method arguments number
  • if method is variadic, the segments mapping to last argument could be zero
  • otherwise, "404 not found" will be returned

some examples:

path method arguments(exclude *gin.Context)
/ REQUEST METHOD nil
/foo foo nil
/foo/bar foo [bar]
/foo/bar/123 foo [bar,123]

License

the project is under MIT license protected which you can find in LICENSE file.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1873 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传