基于 Gin 进行模块化设计的 API 框架,封装了常用功能,使用简单,致力于进行快速的业务研发

关于

go-gin-api 是基于 Gin 进行模块化设计的 API 框架,封装了常用的功能,使用简单,致力于进行快速的业务研发,同时增加了更多限制,约束项目组开发成员,规避混乱无序及自由随意的编码。

供参考学习,线上使用请谨慎!

集成组件:

  1. 支持 rate 接口限流
  2. 支持 panic 异常时邮件通知
  3. 支持 cors 接口跨域
  4. 支持 Prometheus 指标记录
  5. 支持 Swagger 接口文档生成
  6. 支持 GraphQL 查询语言
  7. 支持 trace 项目内部链路追踪
  8. 支持 pprof 性能剖析
  9. 支持 errno 统一定义错误码
  10. 支持 zap 日志收集
  11. 支持 viper 配置文件解析
  12. 支持 gorm 数据库组件
  13. 支持 go-redis 组件
  14. 支持 RESTful API 返回值规范
  15. 支持 生成数据表 CURD、控制器方法 等代码生成器
  16. 支持 cron 定时任务,在后台可界面配置
  17. 支持 websocket 实时通讯,在后台有界面演示
  18. 支持 web 界面,使用的 Light Year Admin 模板

文档索引

其他

查看 Jaeger 链路追踪 Demo 代码,请查看 v1.0 版 ,链接地址:http://127.0.0.1:9999/jaeger_test

调用的其他服务端 Demo 代码为 https://github.com/xinliangnote/go-jaeger-demo

联系作者

联系作者

Comments
  • 接口定义疑问

    接口定义疑问

    type Hash interface {
    	i()
    
    	// hashids
    	HashidsEncode(params []int) (string, error)
    	HashidsDecode(hash string) ([]int, error)
    }
    

    为何我看到在您的项目中有大量的类似这样的接口定义,i() 这个方法在实现的时候又是一个空的方法,这样做有什么含义么?

  • 运行点击仪表盘报错

    运行点击仪表盘报错

    image

    2021/04/23 14:55:45 d:/code/go-gin-api/internal/api/repository/db_repo/admin_repo/gen_admin.go:98 SLOW SQL >= 200ms [4670.267ms] [rows:1] SELECT * FROM admin WHERE is_deleted = -1 AND id = 1 AND is_used = 1 LIMIT 1 {"level":"info","time":"2021-04-23 14:55:45","caller":"core/core.go:474","msg":"core-interceptor","domain":"go-gin-api[fat]","method":"GET","path":"/api/admin/info","http_code":200,"business_code":0,"success":true,"cost_seconds":4.6732673,"trace_id":"f62139a047da777a36ac","trace_info":{"trace_id":"f62139a047da777a36ac","request":{"ttl":"un-limit","method":"GET","decoded_url":"/api/admin/info","header":{"Accept":["/"],"Accept-Encoding":["gzip, deflate, br"],"Accept-Language":["zh-CN,zh;q=0.9"],"Authorization":["admin 1EmSu+IbUb6om7UN0SikDMEkuFVJLICgRRvP5alT88E="],"Authorization-Date":["2021-04-23 14:55:41"],"Connection":["keep-alive"],"Content-Type":["application/x-www-form-urlencoded; charset=utf-8"],"Cookie":["login_token=1ba4686338ee7354395ad13f7d3466c1; the_logo_bg=default; the_header_bg=default; the_sidebar_bg=default; nav_url=%2Fdashboard; nav_title=%20%E4%BB%AA%E8%A1%A8%E7%9B%98"],"Referer":["http://127.0.0.1:9999/"],"Sec-Ch-Ua":[""Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99""],"Sec-Ch-Ua-Mobile":["?0"],"Sec-Fetch-Dest":["empty"],"Sec-Fetch-Mode":["cors"],"Sec-Fetch-Site":["same-origin"],"Token":["1ba4686338ee7354395ad13f7d3466c1"],"User-Agent":["Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36"],"X-Requested-With":["XMLHttpRequest"]},"body":""},"response":{"header":{"Content-Type":["application/json; charset=utf-8"],"Trace-Id":["f62139a047da777a36ac"],"Vary":["Origin"]},"body":{"username":"admin","nickname":"管理员","mobile":"13888888888"},"http_code":200,"http_code_msg":"OK","cost_seconds":4.6732673},"third_party_requests":null,"debugs":null,"sqls":[{"timestamp":"2021-04-23 14:55:45","stack":"d:/code/go-gin-api/internal/api/repository/db_repo/admin_repo/gen_admin.go:98","sql":"SELECT * FROM admin WHERE is_deleted = -1 AND id = 1 AND is_used = 1 LIMIT 1","rows_affected":1,"cost_seconds":4.6702672}],"redis":[{"timestamp":"2021-04-23 14:55:41","handle":"get","key":"go-gin-api:admin:1ba4686338ee7354395ad13f7d3466c1","cost_seconds":0},{"timestamp":"2021-04-23 14:55:41","handle":"get","key":"go-gin-api:authorized:admin","cost_seconds":0.001}],"grpc":null,"success":true,"cost_seconds":4.6732673}} {"level":"error","time":"2021-04-23 14:55:46","caller":"core/core.go:359","msg":"got panic","domain":"go-gin-api[fat]","panic":"runtime error: index out of range [0] with length 0","stack":"goroutine 87 [running]:\nruntime/debug.Stack(0x0, 0x0, 0x0)\n\tF:/Go/install/src/runtime/debug/stack.go:24 +0xac\ngithub.com/xinliangnote/go-gin-api/internal/pkg/core.New.func2.1(0xc000342360, 0x15170d0, 0xc000388d08, 0xc00168e690, 0xc001640000, 0xc018b9bb4d38149c, 0x178a9cddd, 0x2b80560)\n\td:/code/go-gin-api/internal/pkg/core/core.go:358 +0x7e\npanic(0x138d100, 0xc0019c84e0)\n\tF:/Go/install/src/runtime/panic.go:971 +0x4e6\ngithub.com/xinliangnote/go-gin-api/internal/web/controller/dashboard_handler.(*handler).View.func1(0x15170d0, 0xc0001541d8)\n\td:/code/go-gin-api/internal/web/controller/dashboard_handler/func_view.go:73 +0x107a\ngithub.com/xinliangnote/go-gin-api/internal/pkg/core.wrapHandlers.func1(0xc001640000)\n\td:/code/go-gin-api/internal/pkg/core/core.go:214 +0xcb\ngithub.com/gin-gonic/gin.(*Context).Next(0xc001640000)\n\tF:/Go/GOPATH/pkg/mod/github.com/gin-gonic/[email protected]/context.go:161 +0x9c\ngithub.com/xinliangnote/go-gin-api/internal/pkg/core.New.func3(0xc001640000)\n\td:/code/go-gin-api/internal/pkg/core/core.go:505 +0xec\ngithub.com/gin-gonic/gin.(*Context).Next(0xc001640000)\n\tF:/Go/GOPATH/pkg/mod/github.com/gin-gonic/[email protected]/context.go:161 +0x9c\ngithub.com/xinliangnote/go-gin-api/internal/pkg/core.New.func2(0xc001640000)\n\td:/code/go-gin-api/internal/pkg/core/core.go:487 +0x285\ngithub.com/gin-gonic/gin.(*Context).Next(0xc001640000)\n\tF:/Go/GOPATH/pkg/mod/github.com/gin-gonic/[email protected]/context.go:161 +0x9c\ngithub.com/xinliangnote/go-gin-api/internal/pkg/core.New.func1(0xc001640000)\n\td:/code/go-gin-api/internal/pkg/core/core.go:336 +0x6d\ngithub.com/gin-gonic/gin.(*Context).Next(0xc001640000)\n\tF:/Go/GOPATH/pkg/mod/github.com/gin-gonic/[email protected]/context.go:161 +0x9c\ngithub.com/gin-gonic/gin.(*Engine).handleHTTPRequest(0xc0003a0140, 0xc001640000)\n\tF:/Go/GOPATH/pkg/mod/github.com/gin-gonic/[email protected]/gin.go:409 +0x46e\ngithub.com/gin-gonic/gin.(*Engine).ServeHTTP(0xc0003a0140, 0x1505ea0, 0xc001638a80, 0xc000193800)\n\tF:/Go/GOPATH/pkg/mod/github.com/gin-gonic/[email protected]/gin.go:367 +0xe5\ngithub.com/xinliangnote/go-gin-api/internal/pkg/core.(*mux).ServeHTTP(0xc00008e150, 0x1505ea0, 0xc001638a80, 0xc000193800)\n\td:/code/go-gin-api/internal/pkg/core/core.go:234 +0x5a\nnet/http.serverHandler.ServeHTTP(0xc00024a0e0, 0x1505ea0, 0xc001638a80, 0xc000193800)\n\tF:/Go/install/src/net/http/server.go:2887 +0x22b\nnet/http.(*conn).serve(0xc00034a6e0, 0x1507f10, 0xc0015a8340)\n\tF:/Go/install/src/net/http/server.go:1952 +0x1c25\ncreated by net/http.(*Server).Serve\n\tF:/Go/install/src/net/http/server.go:3013 +0x974\n"} {"level":"error","time":"2021-04-23 14:55:46","caller":"notify/notify.go:15","msg":"Mail config error","domain":"go-gin-api[fat]"}

  • build 后直接执行报错

    build 后直接执行报错

    问题描述 go build 编译出 main 后直接执行 main ,系统报错 `./main -env fat

    2022/03/08 02:03:10 /.../go-gin-api/internal/repository/mysql/mysql.go:96 [error] failed to initialize database, got error Error 1045: Access denied for user 'root'@'172.17.0.1' (using password: YES)`

    问题出现的环境背景及自己尝试过哪些方法 系统环境是 linux mint (ubuntu) 如果执行 go run main.go 是成功的,但是编译后执行就失败。 报错信息中显示的 172.17.0.1 地址是docker网卡地址,说明它没有找到正确的配置文件

  • docker file 无法构建

    docker file 无法构建

    /opt/repo/pkg/mod/github.com/go-playground/[email protected]/errors.go:7:2: github.com/go-playground/[email protected]: http2: server sent GOAWAY and closed the connection; LastStreamID=1999, ErrCode=NO_ERROR, debug="" internal/pkg/validation/validation.go:9:2: github.com/go-playground/[email protected]: http2: server sent GOAWAY and closed the connection; LastStreamID=1999, ErrCode=NO_ERROR, debug="" internal/pkg/validation/validation.go:10:2: github.com/go-playground/[email protected]: http2: server sent GOAWAY and closed the connection; LastStreamID=1999, ErrCode=NO_ERROR, debug=""

    未修改docker file

  • 少了个跨域中间件吧

    少了个跨域中间件吧

    在login页面调用/api/login接口直接跨域了

    package middleware
    
    import (
    	"collectlogs/internal/pkg/core"
    )
    
    type HandlerFunc func()
    
    // 处理跨域请求,支持options访问
    func (m *middleware) Cors() core.HandlerFunc {
    	return func(c core.Context) {
    		c.SetHeader("Access-Control-Allow-Origin", "*")
    		c.SetHeader("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id")
    		c.SetHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
    		c.SetHeader("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
    		c.SetHeader("Access-Control-Allow-Credentials", "true")
    
    		return
    	}
    }
    

    还有一个问题就是放在路由下的中间件,我不写调用方法都直接被调用了.感觉这样不太好.

  • 建议支持多种数据库:例如Postgresql和Oracle

    建议支持多种数据库:例如Postgresql和Oracle

    以下基于commit:9aa0067e07d036b4ae57168d2bd138d142dff80e 建议使用gorm在程序初始化的时候创建表,eg:

    type User struct {
    	//通过在字段后面的标签说明,定义golang字段和表字段的关系
    	//例如 `gorm:"column:username"` 标签说明含义是: Mysql表的列名(字段名)为username
    	//这里golang定义的Username变量和MYSQL表字段username一样,他们的名字可以不一样。
    	Id int64 `gorm:"column:username;not null;type:int(4) primary key auto_increment;comment:'用户名'"`
    	Password string `gorm:"column:password;type:varchar(30);index:idx_name"`
    	//创建时间,时间戳
    	CreateTime int64 `gorm:"column:createtime"`
    }
    

    同时建议不要在代码中直接写sql eg:internal/api/controller/tool_handler/func_tables.go:48 切换数据库的时候很痛苦 (postgres要在连接的时候指定数据库,Oracle要在连接的时候指定用户) 谢谢

  • Bump github.com/gin-gonic/gin from 1.6.3 to 1.7.0

    Bump github.com/gin-gonic/gin from 1.6.3 to 1.7.0

    Bumps github.com/gin-gonic/gin from 1.6.3 to 1.7.0.

    Release notes

    Sourced from github.com/gin-gonic/gin's releases.

    Release v1.7.0

    BUGFIXES

    • fix compile error from #2572 (#2600)
    • fix: print headers without Authorization header on broken pipe (#2528)
    • fix(tree): reassign fullpath when register new node (#2366)

    ENHANCEMENTS

    • Support params and exact routes without creating conflicts (#2663)
    • chore: improve render string performance (#2365)
    • Sync route tree to httprouter latest code (#2368)
    • chore: rename getQueryCache/getFormCache to initQueryCache/initFormCa (#2375)
    • chore(performance): improve countParams (#2378)
    • Remove some functions that have the same effect as the bytes package (#2387)
    • update:SetMode function (#2321)
    • remove a unused type SecureJSONPrefix (#2391)
    • Add a redirect sample for POST method (#2389)
    • Add CustomRecovery builtin middleware (#2322)
    • binding: avoid 2038 problem on 32-bit architectures (#2450)
    • Prevent panic in Context.GetQuery() when there is no Request (#2412)
    • Add GetUint and GetUint64 method on gin.context (#2487)
    • update content-disposition header to MIME-style (#2512)
    • reduce allocs and improve the render WriteString (#2508)
    • implement ".Unwrap() error" on Error type (#2525) (#2526)
    • Allow bind with a map[string]string (#2484)
    • chore: update tree (#2371)
    • Support binding for slice/array obj [Rewrite] (#2302)
    • basic auth: fix timing oracle (#2609)
    • Add mixed param and non-param paths (port of httprouter#329) (#2663)
    • feat(engine): add trustedproxies and remoteIP (#2632)
    Changelog

    Sourced from github.com/gin-gonic/gin's changelog.

    Gin v1.7.0

    BUGFIXES

    • fix compile error from #2572 (#2600)
    • fix: print headers without Authorization header on broken pipe (#2528)
    • fix(tree): reassign fullpath when register new node (#2366)

    ENHANCEMENTS

    • Support params and exact routes without creating conflicts (#2663)
    • chore: improve render string performance (#2365)
    • Sync route tree to httprouter latest code (#2368)
    • chore: rename getQueryCache/getFormCache to initQueryCache/initFormCa (#2375)
    • chore(performance): improve countParams (#2378)
    • Remove some functions that have the same effect as the bytes package (#2387)
    • update:SetMode function (#2321)
    • remove a unused type SecureJSONPrefix (#2391)
    • Add a redirect sample for POST method (#2389)
    • Add CustomRecovery builtin middleware (#2322)
    • binding: avoid 2038 problem on 32-bit architectures (#2450)
    • Prevent panic in Context.GetQuery() when there is no Request (#2412)
    • Add GetUint and GetUint64 method on gin.context (#2487)
    • update content-disposition header to MIME-style (#2512)
    • reduce allocs and improve the render WriteString (#2508)
    • implement ".Unwrap() error" on Error type (#2525) (#2526)
    • Allow bind with a map[string]string (#2484)
    • chore: update tree (#2371)
    • Support binding for slice/array obj [Rewrite] (#2302)
    • basic auth: fix timing oracle (#2609)
    • Add mixed param and non-param paths (port of httprouter#329) (#2663)
    • feat(engine): add trustedproxies and remoteIP (#2632)
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

  • 和gin-vue-admin功能打通的问题

    和gin-vue-admin功能打通的问题

    在使用中遇到个问题,接口开发使用的是go_gin_api,管理后台使用的是gin-vue-admin, 1、发现公用的字段 IsDeleted int32 // 是否删除 1:是 -1:否 CreatedAt time.Time gorm:"time" // 创建时间 UpdatedAt time.Time gorm:"time" // 更新时间 上述三个字段中,在go_gin_api中IsDeleted对应的gin-vue-admin的DeletedAt,字段没有打通,无法一起使用,如果可以,能否实现用户选择使用DeletedAt或者IsDeleted来标记数据删除

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
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
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
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
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
Percobaan membuat API dengan Golang menggunakan web framework Gin dan Swagger docs.
Percobaan membuat API dengan Golang menggunakan web framework Gin dan Swagger docs.

Percobaan Gin Framework Percobaan membuat API dengan bahasa Go-lang. Tech Stack Gin - Web framework Gin Swaggo - Swagger Docs integration for Gin web

Feb 11, 2022
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
用来显示 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
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
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
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
Gin middleware/handler to enable CORS support.

wcors Gin middleware/handler to enable CORS support. Usage Start using it Download and install it: go get github.com/wyy-go/wcors Import it in your co

Jan 8, 2022
弹弹play 资源搜索节点 API 实现,基于 Cloudflare Workers 或 Golang 的两种实现。 || API implementations for "dandanplay" resource search service.

dandanplay-resource-service API implementations for "dandanplay" resource search service. 弹弹play 资源搜索节点的 API 实现。 提供基于 Cloudflare Workers 和 Golang 的两种实

Dec 5, 2022