A powerful cli tool to implement gin annotation
- Using code generating technology by operating golang AST
- Routing group
- Enable Aspect Oriented Programming for gin by middleware annotation
- Installation.
go get github.com/1-st/gin-annotation
- Write your HandlerFunc anywhere.
source code files see dir: _example/simple
// controller/hello.go
package controller
/* Hello a simple controller
[
method:GET,
groups:/api,
path:/hello-world,
need:auth
]
*/
func HelloWorld(ctx *gin.Context) {
ctx.JSON(http.StatusOK, map[string]string{
"msg": "hello, world",
})
}
// middleware/auth.go
package middleware
/* Auth a simple middleware
[
id:auth
]
*/
func Auth(ctx *gin.Context) {
ctx.Next()
}
/* Log the first middleware in group /api
[
id:log,
group:/api@1
]
*/
func Log(ctx *gin.Context) {
fmt.Println(ctx.ClientIP())
}
- Run gin-annotation at dir: _example/simple: (you can specify multiple folders)
$ gin-annotation ./
$ ls
controller main.go route.entry.go(!!!new file)
tips: the name of new file is decided by environment variable GIN_ANNOTATION_FILE , default is route.entry.go
- Look at the generated routing file
package main
import (
"gin-annotation/_example/simple/controller"
"gin-annotation/_example/simple/middleware"
"github.com/gin-gonic/gin"
)
func Route(e *gin.Engine) {
api := e.Group("/api", middleware.Log)
{
v1 := api.Group("/v1")
{
v1.GET("/hello-world", middleware.Auth, controller.HelloWorld)
}
}
}
- The last step , call Route() at main.go
package main
import (
"github.com/gin-gonic/gin"
"path"
)
func main() {
e := gin.Default()
Route(e)
_ = e.Run("ip:port")
}
Each groups-annotation consists of multiple groups separated by spaces.
The last element of path.
GET,POST,DELETE,PATCH,OPTIONS or ANY.
need:id1 id2,
Each element of need-annotation is the id of the middleware.
The unique id of middleware.
/* example
[
id:example,
group:/api/v1/@1,
group:/api/v2/@1
]
*/
Each middleware can have multiple group-annotations,
The number behind @ is the priority of middleware.
- Don't write extra "," in the last item of an annotation.
/* example
[
id:example,
group:/api/v1/@1 <- here
]
*/