GithubHelp home page GithubHelp logo

xxjwxc / ginrpc Goto Github PK

View Code? Open in Web Editor NEW
287.0 9.0 36.0 27.91 MB

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

Home Page: https://xxjwxc.github.io/post/ginrpc/

License: Apache License 2.0

Go 99.62% Makefile 0.38%
gin golang auto bind go rpc binding middleware grpc grpc-go

ginrpc's Introduction

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 

  • @Router - [-] indicates ignore

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

ginrpc's People

Contributors

dependabot[bot] avatar xxjwxc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ginrpc's Issues

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

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

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

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

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

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

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

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

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

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之类的

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

不知道算不算问题哈

  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 这种参数来生成到文档中

感谢

but does not contain package

github.com/xxjwxc/ginrpc/api: module github.com/xxjwxc/ginrpc@latest found (v1.0.0), but does not contain package github.com/xxjwxc/ginrpc/api

无法生成gmsec/routers

D:\01-program\golang\ginrpc>go run main.go
main.go:7:2: package gmsec/routers is not in GOROOT (c:\go\src\gmsec\routers)

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"`
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.