Gin best practices, gin development scaffolding, too late to explain, get on the bus.

Table of Contents generated with DocToc

gin_scaffold

Gin best practices, gin development scaffolding, too late to explain, get on the bus.

使用gin构建了企业级脚手架,代码简洁易读,可快速进行高效web开发。 主要功能有:

  1. 请求链路日志打印,涵盖mysql/redis/request
  2. 支持多语言错误信息提示及自定义错误提示。
  3. 支持了多配置环境
  4. 封装了 log/redis/mysql/http.client 常用方法
  5. 支持swagger文档生成

项目地址:https://github.com/e421083458/gin_scaffold

现在开始

  • 安装软件依赖 go mod使用请查阅:

https://blog.csdn.net/e421083458/article/details/89762113

git clone [email protected]:e421083458/gin_scaffold.git
cd gin_scaffold
go mod tidy
  • 确保正确配置了 conf/mysql_map.toml、conf/redis_map.toml:

  • 运行脚本

go run main.go

➜  gin_scaffold git:(master) ✗ go run main.go
------------------------------------------------------------------------
[INFO]  config=./conf/dev/
[INFO]  start loading resources.
[INFO]  success loading resources.
------------------------------------------------------------------------
[GIN-debug] [WARNING] Now Gin requires Go 1.6 or later and Go 1.7 will be required soon.

[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:	export GIN_MODE=release
 - using code:	gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /demo/index               --> github.com/e421083458/gin_scaffold/controller.(*Demo).Index-fm (6 handlers)
[GIN-debug] GET    /demo/bind                --> github.com/e421083458/gin_scaffold/controller.(*Demo).Bind-fm (6 handlers)
[GIN-debug] GET    /demo/dao                 --> github.com/e421083458/gin_scaffold/controller.(*Demo).Dao-fm (6 handlers)
[GIN-debug] GET    /demo/redis               --> github.com/e421083458/gin_scaffold/controller.(*Demo).Redis-fm (6 handlers)
 [INFO] HttpServerRun::8880
  • 测试mysql与请求链路

创建测试表:

CREATE TABLE `area` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `area_name` varchar(255) NOT NULL,
 `city_id` int(11) NOT NULL,
 `user_id` int(11) NOT NULL,
 `update_at` datetime NOT NULL,
 `create_at` datetime NOT NULL,
 `delete_at` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='area';
INSERT INTO `area` (`id`, `area_name`, `city_id`, `user_id`, `update_at`, `create_at`, `delete_at`) VALUES (NULL, 'area_name', '1', '2', '2019-06-15 00:00:00', '2019-06-15 00:00:00', '2019-06-15 00:00:00');
curl 'http://127.0.0.1:8880/demo/dao?id=1'
{
    "errno": 0,
    "errmsg": "",
    "data": "[{\"id\":1,\"area_name\":\"area_name\",\"city_id\":1,\"user_id\":2,\"update_at\":\"2019-06-15T00:00:00+08:00\",\"create_at\":\"2019-06-15T00:00:00+08:00\",\"delete_at\":\"2019-06-15T00:00:00+08:00\"}]",
    "trace_id": "c0a8fe445d05b9eeee780f9f5a8581b0"
}

查看链路日志(确认是不是一次请求查询,都带有相同trace_id):
tail -f gin_scaffold.inf.log

[INFO][2019-06-16T11:39:26.802][log.go:58] _com_request_in||method=GET||from=127.0.0.1||traceid=c0a8fe445d05b9eeee780f9f5a8581b0||cspanid=||uri=/demo/dao?id=1||args=map[]||body=||spanid=9dad47aa57e9d186
[INFO][2019-06-16T11:39:26.802][log.go:58] _com_mysql_success||affected_row=1||traceid=c0a8fe445d05b9ee07b80f9f66cb39b0||spanid=9dad47aa1408d2ac||source=/Users/niuyufu/go/src/github.com/e421083458/gin_scaffold/dao/demo.go:24||proc_time=0.000000000||sql=SELECT * FROM `area`  WHERE (id = '1')||level=sql||current_time=2019-06-16 11:39:26||cspanid=
[INFO][2019-06-16T11:39:26.802][log.go:58] _com_request_out||method=GET||args=map[]||proc_time=0.025019164||traceid=c0a8fe445d05b9eeee780f9f5a8581b0||spanid=9dad47aa57e9d186||uri=/demo/dao?id=1||from=127.0.0.1||response={\"errno\":0,\"errmsg\":\"\",\"data\":\"[{\\\"id\\\":1,\\\"area_name\\\":\\\"area_name\\\",\\\"city_id\\\":1,\\\"user_id\\\":2,\\\"update_at\\\":\\\"2019-06-15T00:00:00+08:00\\\",\\\"create_at\\\":\\\"2019-06-15T00:00:00+08:00\\\",\\\"delete_at\\\":\\\"2019-06-15T00:00:00+08:00\\\"}]\",\"trace_id\":\"c0a8fe445d05b9eeee780f9f5a8581b0\"}||cspanid=
  • 测试参数绑定与多语言验证
curl 'http://127.0.0.1:8880/demo/bind?name=name&locale=zh'
{
    "errno": 500,
    "errmsg": "年龄为必填字段,密码为必填字段",
    "data": "",
    "trace_id": "c0a8fe445d05badae8c00f9fb62158b0"
}

curl 'http://127.0.0.1:8880/demo/bind?name=name&locale=en'
{
    "errno": 500,
    "errmsg": "Age is a required field,Passwd is a required field",
    "data": "",
    "trace_id": "c0a8fe445d05bb4cd3b00f9f3a768bb0"
}

文件分层

├── README.md
├── conf            配置文件夹
│   └── dev
│       ├── base.toml
│       ├── mysql_map.toml
│       └── redis_map.toml
├── controller      控制器
│   └── demo.go
├── dao             DB数据层
│   └── demo.go
├── docs            swagger文件层
├── dto             输入输出结构层
│   └── demo.go
├── go.mod
├── go.sum
├── main.go         入口文件
├── middleware      中间件层
│   ├── panic.go
│   ├── response.go
│   ├── token_auth.go
│   └── translation.go
├── public          公共文件
│   ├── log.go
│   ├── mysql.go
│   └── validate.go
└── router          路由层
    ├── httpserver.go
    └── route.go

log / redis / mysql / http.client 常用方法

参考文档:https://github.com/e421083458/golang_common

swagger文档生成

https://github.com/swaggo/swag/releases

  • 下载对应操作系统的执行文件到$GOPATH/bin下面

如下:

➜  gin_scaffold git:(master) ✗ ll -r $GOPATH/bin
total 434168
-rwxr-xr-x  1 niuyufu  staff    13M  4  3 17:38 swag
  • 设置接口文档参考: controller/demo.go 的 Bind方法的注释设置
// ListPage godoc
// @Summary 测试数据绑定
// @Description 测试数据绑定
// @Tags 用户
// @ID /demo/bind
// @Accept  json
// @Produce  json
// @Param polygon body dto.DemoInput true "body"
// @Success 200 {object} middleware.Response{data=dto.DemoInput} "success"
// @Router /demo/bind [post]
Similar Resources

Kubectl-explore - A kubectl plugin for fuzzy-find fields to explain.

kubectl-explore This command is a better kubectl explain with the fuzzy-finder. What kubectl-explore finds fields associated with each supported API r

Dec 29, 2022

Microservice framework following best cloud practices with a focus on productivity.

patron Patron is a framework for creating microservices, originally created by Sotiris Mantzaris (https://github.com/mantzas). This fork is maintained

Dec 22, 2022

Logur is an opinionated collection of logging best practices

Logur is an opinionated collection of logging best practices

Logur is an opinionated collection of logging best practices. Table of Contents Preface Features Installation Usage FAQ Why not just X logger? Why not

Dec 30, 2022

Validation of best practices in your Kubernetes clusters

Validation of best practices in your Kubernetes clusters

Best Practices for Kubernetes Workload Configuration Fairwinds' Polaris keeps your clusters sailing smoothly. It runs a variety of checks to ensure th

Jan 9, 2023

A best practices checker for Kubernetes clusters. 🤠

Clusterlint As clusters scale and become increasingly difficult to maintain, clusterlint helps operators conform to Kubernetes best practices around r

Dec 29, 2022

Music recognition bot for Reddit powered by audd.io. Note that the code currently needs some cleaning up and doesn't follow the best practices.

Music recognition bot for Reddit u/auddbot identifies music on Reddit. When someone mentions it or writes a question like "what's the song", it sends

Dec 30, 2022

Go Server/API boilerplate using best practices DDD CQRS ES gRPC

Go Server/API boilerplate using best practices DDD CQRS ES gRPC

Go Server/API boilerplate using best practices DDD CQRS ES gRPC

Jan 6, 2023

OpenResty Best Practices

OpenResty Best Practices

OpenResty 最佳实践 我们提供 OpenResty、Apache APISIX 以及 API 网关方面相关的咨询、培训、性能优化、定制开发等商业支持服务,欢迎联系。

Jan 2, 2023

A cookbook with the best practices to working with kubernetes.

A cookbook with the best practices to working with kubernetes.

A cookbook with the best practices to working with kubernetes.

Dec 27, 2022

This plugin will analyse the JFrog Platform instance and provide the non conformance against the best practices based on the predefines rules.

hello-frog About this plugin This plugin is a template and a functioning example for a basic JFrog CLI plugin. This README shows the expected structur

Nov 30, 2021

Golang service boilerplate using best practices

go-boilerplate Golang service boilerplate using best practices. Responsibility: Register (CRUD) and Login Users with JWT. Dependencies Gin-Gonic Swagg

May 11, 2022

A guide to smart contract security best practices

Smart Contract Security Best Practices Visit the documentation site: https://consensys.github.io/smart-contract-best-practices/ Read the docs in Chine

Dec 27, 2022

Easily kick-start your python project with very opinionated best practices.

Pyproject Easily kickstart your Python project with very opionionated best practices. Manage your project using poetry https://python-poetry.org/ Add

Jan 24, 2022

AI-Powered Code Reviews for Best Practices & Security Issues Across Languages

AI-Powered Code Reviews for Best Practices & Security Issues Across Languages

AI-CodeWise 🦉 AI-Powered Code Reviews for Best Practices & Security Issues Across Languages AI-CodeWise GitHub Action: Your AI-powered Code Reviewer!

May 11, 2023

RBAC scaffolding based on Gin + Gorm+ Casbin + Wire

RBAC scaffolding based on Gin + Gorm+ Casbin + Wire

Gin Admin 基于 GIN + GORM + CASBIN + WIRE 实现的RBAC权限管理脚手架,目的是提供一套轻量的中后台开发框架,方便、快速的完成业务需求的开发。 特性 遵循 RESTful API 设计规范 & 基于接口的编程规范 基于 GIN 框架,提供了丰富的中间件支持(JWT

Dec 28, 2022

DockerSlim (docker-slim): Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)

DockerSlim (docker-slim): Don't change anything in your Docker container image and minify it by up to 30x (and for compiled languages even more) making it secure too! (free and open source)

Minify and Secure Docker containers (free and open source!) Don't change anything in your Docker container image and minify it by up to 30x making it

Dec 27, 2022

Parse data and test fixtures from markdown files, and patch them programmatically, too.

go-testmark Do you need test fixtures and example data for your project, in a language agnostic way? Do you want it to be easy to combine with documen

Oct 31, 2022

Spawning up Decoy Server in case of any fraudulent activity and directing the intruder towards the decoy. Auto Killing the decoy if it is idle for too long.

Spawning up Decoy Server in case of any fraudulent activity and directing the intruder towards the decoy. Auto Killing the decoy if it is idle for too long.

SecureX Spawning up Decoy Server in case of any fraudulent activity and directing the intruder towards the decoy. Auto Killing the decoy if it is idle

Jul 9, 2022

CoachCarter: a discord bot which lets a server know if its inactive for too long

CoachCarter: a discord bot which lets a server know if its inactive for too long

I took this job because I wanted to affect change in a special group of young me

Jan 7, 2022
Comments
  • cannot find module

    cannot find module

    run go mod tidy,error message is : github.com/e421083458/gin_scaffold/docs: cannot find module providing package github.com/e421083458/gin_scaffold/docs

    how to resolve?

  • trace_id 是变动的,mysql 的 和 request_in  和 request_out 的不一样

    trace_id 是变动的,mysql 的 和 request_in 和 request_out 的不一样

    [INFO][2020-01-06T15:37:34.204][log.go:58] _com_request_in||method=GET||body=||from=127.0.0.1||traceid=a9fe0fb65e12e3be9f4c1a90b62158b0||cspanid=||spanid=f7ecec083c04951a||uri=/demo/dao?id=1||args=map[] [INFO][2020-01-06T15:37:34.204][log.go:58] _com_mysql_success||sql=SELECT * FROM area WHERE (id = '1')||cspanid=||spanid=f7ecec0825845c95||source=D:/golang/gin_scaffold/dao/demo.go:24||current_time=2020-01-06 15:37:34||affected_row=0||traceid=a9fe0fb65e12e3be47941a903a768bb0||level=sql||proc_time=0.000000000 [INFO][2020-01-06T15:37:34.204][log.go:58] _com_request_out||proc_time=0.0029922||traceid=a9fe0fb65e12e3be9f4c1a90b62158b0||cspanid=||uri=/demo/dao?id=1||method=GET||args=map[]||from=127.0.0.1||response={"errno":0,"errmsg":"","data":"[]","trace_id":"a9fe0fb65e12e3be9f4c1a90b62158b0"}||spanid=f7ecec083c04951a

  • 报错:invalid value, should be pointer to struct or slice

    报错:invalid value, should be pointer to struct or slice

    func (f *User) Find(c *gin.Context, tx *gorm.DB, id int64) (*User, error) { var user *User err := tx.WithContext(c).Where("id = ?", id).First(user).Error if err != nil { return nil, err } return user, nil }

    var user *User改成var user &User{}

  • The process cannot access the file because it is being used by another process.

    The process cannot access the file because it is being used by another process.

    2022/04/04 12:00:07 rename ./logs/gin_scaffold.inf.log ./logs/gin_scaffold.inf.log.2022040411: The process cannot access the file because it is being used by another process.

    日志切割存在以上问题,请问如何解决?

Native Go bindings for D-Bus

dbus dbus is a simple library that implements native Go client bindings for the D-Bus message bus system. Features Complete native implementation of t

Dec 30, 2022
Go simple async message bus
Go simple async message bus

?? message-bus Go simple async message bus. ?? ABOUT Contributors: Rafał Lorenz Want to contribute ? Feel free to send pull requests! Have problems, b

Dec 29, 2022
Easy to use distributed event bus similar to Kafka
Easy to use distributed event bus similar to Kafka

chukcha Easy to use distributed event bus similar to Kafka. The event bus is designed to be used as a persistent intermediate storage buffer for any k

Dec 30, 2022
Govent is an event bus framework for DDD event source implement

Govent is an event bus framework for DDD event source implement. Govent can also solve the package circular dependency problem.

Jan 28, 2022
Messagebus - Simple Message Bus Written in Golang

MessageBus Simple Message Bus Written in Golang How to Use go get gopkg.io/Usada

Apr 21, 2022
Basic Event Streaming - Fundamentals of Kafka Studies (BESt-FunKS)

Apache Kafka My study repo for Apache Kafka. Based on this tutorial. Contents Overview Key Terms Event Topic Producer Consumer Partition Getting Start

Mar 2, 2022
Inspr is an application mesh for simple, fast and secure development of distributed applications.
Inspr is an application mesh for simple, fast and secure development of distributed applications.

Inspr is an engine for running distributed applications, using multiple communication patterns such as pub sub and more, focused on type consistency a

Jun 10, 2022
A blank project for Go development with CDK

Welcome to your CDK Go project! This is a blank project for Go development with CDK. NOTICE: Go support is still in Developer Preview. This implies th

Nov 26, 2021
A best practices Go source project with unit-test and integration test, also use skaffold & helm to automate CI & CD at local to optimize development cycle

Dependencies Docker Go 1.17 MySQL 8.0.25 Bootstrap Run chmod +x start.sh if start.sh script does not have privileged to run Run ./start.sh --bootstrap

Apr 4, 2022
Search and store the best cryptos for the best scalable and modern application development.

Invst Hunt Search and store the best cryptos for the best scalable and modern application development. Layout Creating... Project Challenge The Techni

Nov 12, 2021