gin auto binding,grpc, and annotated route,gin 注解路由, grpc,自动参数绑定工具

Build Status Go Report Card codecov GoDoc Mentioned in Awesome Go

中文文档

Automatic parameter binding base on go-gin

img

doc

doc

Golang gin automatic parameter binding

  • Support for RPC automatic mapping

  • Support object registration

  • Support annotation routing

  • base on go-gin on json restful style

  • implementation of parameter filtering and binding with request

  • code registration simple and supports multiple ways of registration

  • grpc-go bind support

  • Support swagger MORE

  • Support markdown/mindoc MORE

  • Support call before and after deal(ginrpc.WithBeforeAfter)

  • DEMO

Installing

  • go mod:
go get -u github.com/xxjwxc/ginrpc@master

API details

Three interface modes are supported

  • func(*gin.Context) // go-gin Raw interface

    func(*api.Context) // Custom context type

  • func(*api.Context,req) // Custom context type,with request

    func(*api.Context,*req)

  • func(*gin.Context,*req) // go-gin context,with request

    func(*gin.Context,req)

  • func(*gin.Context,*req)(*resp,error) // go-gin context,with request,return parameter and error ==> grpc-go

    func(*gin.Context,req)(resp,error)

一. Parameter auto binding,Object registration (annotation routing)

Initialization project (this project is named after gmsec)

``` go mod init gmsec ```

coding more>>

package main

import (
	"fmt"
	"net/http"

	_ "gmsec/routers" // Debug mode requires adding [mod] / routes to register annotation routes.debug模式需要添加[mod]/routers 注册注解路由
	"github.com/xxjwxc/public/mydoc/myswagger" // swagger 支持

	"github.com/gin-gonic/gin"
	"github.com/xxjwxc/ginrpc"
	"github.com/xxjwxc/ginrpc/api"
)

type ReqTest struct {
	Access_token string `json:"access_token"`
	UserName     string `json:"user_name" binding:"required"` // With verification mode
	Password     string `json:"password"`
}

// Hello ...
type Hello struct {
}

// Hello Annotated route (bese on beego way)
// @Router /block [post,get]
func (s *Hello) Hello(c *api.Context, req *ReqTest) {
	fmt.Println(req)
	c.JSON(http.StatusOK, "ok")
}

// Hello2 Route without annotation (the parameter is 2 default post)
func (s *Hello) Hello2(c *gin.Context, req ReqTest) {
	fmt.Println(req)
	c.JSON(http.StatusOK, "ok")
}

// [grpc-go](https://github.com/grpc/grpc-go)
// with request,return parameter and error
// TestFun6 Route without annotation (the parameter is 2 default post)
func TestFun6(c *gin.Context, req ReqTest) (*ReqTest, error) {
	fmt.Println(req)
	//c.JSON(http.StatusOK, req)
	return &req, nil
}

func main() {

	// swagger
	myswagger.SetHost("https://localhost:8080")
	myswagger.SetBasePath("gmsec")
	myswagger.SetSchemes(true, false)
	// -----end --
	base := ginrpc.New()
	router := gin.Default() // or router :=  gin.Default().Group("/xxjwxc")
	base.Register(router, new(Hello)) // object register like(go-micro)
	router.POST("/test6", base.HandlerFunc(TestFun6))                            // function register
	base.RegisterHandlerFunc(router, []string{"post", "get"}, "/test", TestFun6) 
	router.Run(":8080")
}

- Annotation routing related instructions


// @Router /block [post,get]
@Router tag  
/block router 
[post,get] method 

Note: if there is no annotation route in the object function, the system will add annotation route by default. Post mode: with req (2 parameters (CTX, req)), get mode is a parameter (CTX)

1. Annotation route will automatically create [mod]/routes/gen_router.go file, which needs to be added when calling:

```
_ "[mod]/routers" // Debug mode requires adding [mod] / routes to register annotation routes

```

By default, the [gen_router. Data] file will also be generated in the root directory of the project (keep this file, and you can embed it without adding the above code)

2. way of annotation route :

more to saying  [gmsec](https://github.com/gmsec/gmsec)

3. Parameter description

ginrpc.WithCtx : Set custom context

ginrpc.WithDebug(true) : Set debug mode

ginrpc.WithOutDoc(true) : output markdown/swagger api doc

ginrpc.WithBigCamel(true) : Set big camel standard (false is web mode, _, lowercase)

ginrpc.WithBeforeAfter(&ginrpc.DefaultGinBeforeAfter{}) : Before After call

[more>>](https://godoc.org/github.com/xxjwxc/ginrpc)

4. Execute curl to automatically bind parameters. See the results directly

curl 'http://127.0.0.1:8080/xxjwxc/block' -H 'Content-Type: application/json' -d '{"access_token":"111", "user_name":"222", "password":"333"}'
curl 'http://127.0.0.1:8080/xxjwxc/hello.hello2' -H 'Content-Type: application/json' -d '{"access_token":"111", "user_name":"222", "password":"333"}'

二. swagger/markdown/mindoc Document generation description

	ginrpc.WithOutDoc(true) : output markdown/swagger

1.For object registration 'ginrpc. Register' mode, document export is supported

2.Export supports annotation routing, Parameter annotation and default value (tag '. default')

3.Default export path:(/docs/swagger/swagger.json,/docs/markdown)

4 struct demo

type ReqTest struct {
	AccessToken string `json:"access_token"`
	UserName    string `json:"user_name" binding:"required"` // 带校验方式
	Password    string `json:"password"`
}

三. Support to call Middleware

  • using ginrpc.WithBeforeAfter(&ginrpc.DefaultGinBeforeAfter{})
  • You can also implement functions (single types) on objects
	// GinBeforeAfter Execute middleware before and after the object call (support adding the object separately from the object in total)
	type GinBeforeAfter interface {
		GinBefore(req *GinBeforeAfterInfo) bool
		GinAfter(req *GinBeforeAfterInfo) bool
	}

Stargazers over time

Stargazers over time

coding address:ginprc Please give star support

Comments
  • 自动参数绑定,传参错误时,解析报错

    自动参数绑定,传参错误时,解析报错

    针对自动参数绑定示例,将结构体改为:

    type ReqTest struct {
    	Access_token string `json:"access_token"`
    	UserName     string `json:"user_name" binding:"required"` // With verification mode.带校验方式
    	Password     int `json:"password"`
    }
    

    curl 'http://127.0.0.1:8080/xxjwxc/block' -H 'Content-Type: application/json' -d '{"access_token":"111", "user_name":"222", "password":333}' 正常,执行 curl 'http://127.0.0.1:8080/xxjwxc/block' -H 'Content-Type: application/json' -d '{"access_token":"111", "user_name":"222", "password":"333"}' 报错

    自动参数绑定无法将字符串类型转换为int类型,建议做个兼容 int 2 string string 2 int

  • 路由使用中间件后无法自动注册

    路由使用中间件后无法自动注册

    很多时候分组路由需要添加各种中间做权限等,这个时候经常写

    gAuth := g.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
    	{
    		gAuth.GET("/nilcheckrole", nil)
    		var autoRoute = ginrpc.New()
    		autoRoute.Register(gAuth, new(adminApi.AdminInfos))
    	}
    

    gAuth这个返回的是ginGroup的IRoutes, 导致register的时候类型不匹配, 请问如何处理呢?是否能增加一个RegisterGroup之类的

  • Bind Path Param

    Bind Path Param

    How can I bind PathParam to Struct? Thanks! like, request URI is hello/:id, I wanna bind id to Struct

    type HelloRequest struct {
        Id uint64 `json:"id,omitempty"`
    }
    
  • go get -u github.com/xxjwxc/ginrpc@master

    go get -u github.com/xxjwxc/ginrpc@master

    image github.com/xxjwxc/ginrpc imports github.com/xxjwxc/public/myast: cannot find module providing package github.com/xxjwxc/public/myast github.com/xxjwxc/ginrpc imports github.com/xxjwxc/public/mydoc: cannot find module providing package github.com/xxjwxc/public/mydoc github.com/xxjwxc/ginrpc imports github.com/xxjwxc/public/myreflect: cannot find module providing package github.com/xxjwxc/public/myreflect

  • 您好,认真阅读了您的代码,有些问题请教

    您好,认真阅读了您的代码,有些问题请教

    1.通过ast获取注释,然后自动注册路由和参数绑定。我看代码部分是根据mod 和当前文件目录查找到具体文件,请问在生产环境是否受限,就是打包后发服务器是否可以继续用? 2.参数绑定我目前看到可以传req结构体,但是参数校验,比如新增age参数,然后传0和不传得到的结果是一样的,传一个小数也会接收到0,能否灵活配置,方便更严格的参数校验和参数获取。 另外不止如何添加您的联系方式,非常希望能够加上你一起交流。

  • 基于此库进行了一些修改自用, 发现的几个问题

    基于此库进行了一些修改自用, 发现的几个问题

    不知道算不算问题哈

    1. 建议打个tag, 这样方便go mod项目直接import
    2. gen.go 的方法 genCode没有自动创建routers目录, 如果是直接使用这个库的情况(不是基于gmsec项目), 就会调试时可以注册路由, 到编译成其他系统就不行了
    3. Register方法只能调用一次, 每次调用都会生成swagger.json, 会覆盖之前的文档
    4. 默认情况下会为每个没有写注解的公开方法都生成路由, 这样的话想实现下面这种就比较怪了 会把api.BaseController里的方法也注册起来, 也许可以加个注解比如 @Ignore 忽略路由注册
    type SysUser struct {
    	api.BaseController
    	api.BaseAuthController
    }
    
    1. 目前好像不能声明header query 这种参数来生成到文档中

    感谢

  • Arm64 run panic: package parsing failed:can not find main files

    Arm64 run panic: package parsing failed:can not find main files "runtime/asm_amd64.s"

    if strings.HasSuffix(filename, "runtime/asm_amd64.s") {
    				index = index - 2
    				break
    			}
    			index++
    

    asm_amd64 is not correct in arm64 platform !

    panic: package parsing failed:can not find main files

    goroutine 1 [running]: github.com/xxjwxc/public/myast.GetModuleInfo(0x2, 0x40000740d8, 0x400042baa8, 0x89198, 0x0, 0xe24dc) /go/pkg/mod/github.com/xxjwxc/[email protected]/myast/common.go:42 +0x36c github.com/xxjwxc/ginrpc.(_Base).tryGenRegister(0x40003a0190, 0x8588a0, 0x40003b01a0, 0x400042bea8, 0x1, 0x1, 0x40003a0190) /go/pkg/mod/github.com/xxjwxc/[email protected]/common.go:455 +0x30 github.com/xxjwxc/ginrpc.(_Base).Register(0x40003a0190, 0x8588a0, 0x40003b01a0, 0x400042bea8, 0x1, 0x1, 0x40003b01a0) /go/pkg/mod/github.com/xxjwxc/[email protected]/ginrpc.go:152 +0x9c

Paramex is a library that binds http request parameters to a Go struct annotated with `param`.

paramex Paramex is a library that binds http request parameters to a Go struct annotated with param. Description To extract http parameters (headers,

Oct 31, 2022
Swagger + Gin = SwaGin, a web framework based on Gin and Swagger
Swagger + Gin = SwaGin, a web framework based on Gin and Swagger

Swagger + Gin = SwaGin Introduction SwaGin is a web framework based on Gin and Swagger, which wraps Gin and provides built-in swagger api docs and req

Dec 30, 2022
Swagger + Gin = SwaGin, a web framework based on Gin and Swagger
Swagger + Gin = SwaGin, a web framework based on Gin and Swagger

Swagger + Gin = SwaGin Introduction SwaGin is a web framework based on Gin and Swagger, which wraps Gin and provides built-in swagger api docs and req

Dec 30, 2022
Headless CMS with automatic JSON API. Featuring auto-HTTPS from Let's Encrypt, HTTP/2 Server Push, and flexible server framework written in Go.
Headless CMS with automatic JSON API. Featuring auto-HTTPS from Let's Encrypt, HTTP/2 Server Push, and flexible server framework written in Go.

Ponzu Watch the video introduction Ponzu is a powerful and efficient open-source HTTP server framework and CMS. It provides automatic, free, and secur

Dec 28, 2022
Dec 28, 2022
golang crud restful api with gorm , gin and mysql DB

crud restful api with golang , gorm , gin and mysql this api does a simple CRUD operations on a single table mysql Database . this is build on top off

Feb 26, 2022
Example Golang API backend rest implementation mini project Point Of Sale using Gin Framework and Gorm ORM Database.

Example Golang API backend rest implementation mini project Point Of Sale using Gin Framework and Gorm ORM Database.

Dec 23, 2022
Building basic API with go, gin and gorm

Project Description Terima kasih sudah berkunjung ke halaman repositori ini, repositori ini berisi basic RESTFUL API dengan menggunakan teknologi seba

Nov 20, 2021
GOLF(Go Light Filter), golf dependents Gorm and Gin.

GOLF (WIP) GOLF(Go Light Filter), golf dependents Gorm and Gin. golf can help you build model query as fast as,build model query like Django Rest Fram

Dec 12, 2021
Gin is a HTTP web framework written in Go (Golang).
Gin is a HTTP web framework written in Go (Golang).

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.

Jan 3, 2023
Opinionated Go starter with gin for REST API, logrus for logging, viper for config with added graceful shutdown

go-gin-starter An opinionated starter for Go Backend projects using: gin-gonic/gin as the REST framework logrus for logging viper for configs Docker f

Dec 2, 2022
用来显示 markdown 文档的,基于 gin 框架的, go 语言开发的博客

Bro Qiang 博客 示例: broqiang.com (个人博客,正在使用) 源码: github.com/broqiang/mdblog 提示 此项目已经由 dep 管理更换为 mod 管理 环境 开发环境 Ubuntu 18.04 服务器环境 CentOS 7.6 其他环境没有测试过,不确

Dec 2, 2022
Rocinante is a gin inspired web framework built on top of net/http.

Rocinante Rocinante is a gin inspired web framework built on top of net/http. ⚙️ Installation $ go get -u github.com/fskanokano/rocinante-go ⚡️ Quicks

Jul 27, 2021
The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework.

jin About The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework. If thi

Jul 14, 2022
Template/Starter code for Go application with Gin, System Tray, Gorm, Air, Swagger, JWT

gin-systray-starter Starter code for Go application with Gin, System Tray, Gorm, Air, Swagger, JWT systray, https://github.com/getlantern/systray gin,

Sep 16, 2022
go gin rest api

go-gin-rest-api-f1 go-gin-rest-api Tutorial from: https://golang.org/doc/tutorial/web-service-gin I just used F1 Drivers. go get . to get gin go run .

Oct 20, 2021
A gin-like simple golang web framework.

webgo A gin-like simple golang web framework.

Aug 24, 2022
A gin-like simple golang web framework.

A gin-like simple golang web framework.

Aug 24, 2022
Timeout handler for http request in Gin framework

Middleware to Handle Request Timeout in Gin Installation Installation go get github.com/s-wijaya/gin-timeout Import it in your code: import ( // o

Dec 14, 2021