# gin-api
**Repository Path**: wu--2019/gin-api
## Basic Information
- **Project Name**: gin-api
- **Description**: gin开发的接口系统,包含常用组件:
mysql,redis,mongodb,elasticsearch,jwt,rabbitmq,logrus,sentry,viper,限流,email,上传图片
- **Primary Language**: Go
- **License**: MIT
- **Default Branch**: main
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 2
- **Created**: 2021-05-27
- **Last Updated**: 2021-05-27
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# Gin Project
#### Introduction
The following is a project interface based on gin, including mysql, redis, elasticsearch, mongo, rabbitmq, jaeger, sentry,ratelimiter, jwt, sending mail, uploading pictures, etc. If you are interested, please star, and you can also follow my blog:http://www.cyz.show
#### Directory Structure
~~~
ginpro root directory
├─boot initialize database connection, etc.
├─common initialize database connection, etc.
│ ├─dict data dictionary, error codes and common parameters
│ └─global global variables
├─config system configuration file directory
│ ├─config.go configuration initialization
│ ├─dev.yaml development machine configuration
│ └─qa.yaml test environment configuration
├─docs swagger document directory (the following three files are generated by the swag init command in the root directory)
│ ├─docs.go
│ ├─swagger.json
│ └─swagger.yaml
├─internal
│ ├─api interface
│ ├─dao dao layer, add, delete, modify and check the database
│ ├─middleware middleware
│ ├─model model layer, database field table names, etc.
│ ├─router routing
│ └─service
├─pkg
│ ├─app interface
│ │ ├─app.go interface response and other method packaging
│ │ ├─form.go form validation package
│ │ ├─jwt.go jwt authentication
│ │ └─pagination.go pagination
│ ├─es elasticsearch
│ ├─fasthttp
│ ├─gredis redis
│ ├─helper
│ │ ├─convert Common conversion
│ │ ├─email mail sending
│ │ ├─files file operation related
│ │ ├─gjson json operation
│ │ └─gtime time related operations
│ ├─limiter current limit
│ ├─logger log
│ ├─mgodb mongodb
│ ├─rabbitmq rabbitmq
│ ├─security md5 encryption, etc.
│ └─tracer link tracking
├─storage
│ ├─logs log
│ └─uploads uploaded files
├─go.mod module management
└─main.go entry file
~~~
#### Start the tutorial
1. Install mysql
2. Install jaeger:
```dockerfile
docker run -d --name jaeger \
-e COLLECTOR_ZIPKIN_HTTP_PORT=9411 \
-p 5775:5775/udp \
-p 6831:6831/udp \
-p 6832:6832/udp \
-p 5778:5778 \
-p 16686:16686 \
-p 14268:14268 \
-p 9411:9411 \
jaegertracing/all-in-one:latest
```
3. Install es (the following 3-6 can be selected in the InitApp method of internal/boot/boot.go to decide whether to initialize or not, if you don’t need it, you can comment out the corresponding code)
4. Install redis
5. Install mongo
6. Install rabbitmq
7. Install sentry, if you don’t want to install it, please modify the following code in the pkg/logger/logrus.go file and comment it out
```golang
hook, err := logrus_sentry.NewSentryHook(config.Conf.Sentry.Dsn, []logrus.Level{
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
})
if err == nil {
global.Logger.Hooks.Add(hook)
hook.Timeout = 0
hook.StacktraceConfiguration.Enable = true
}
```
7. Execute ```go mod tidy``` in the project root directory
8. ```go run main.go``` can start
9. In order to facilitate the development, generally use hot update, install fresh, execute ```go get github.com/pilu/fresh``` in the root directory, and then use the fresh command to start, and the second choice of step 9 above One
10. Install swagger, generate documentation, not necessary
```
go get -u github.com/swaggo/swag/cmd/swag@v1.6.5
go get -u github.com/swaggo/gin-swagger@v1.2.0
go get -u github.com/swaggo/files
go get -u github.com/alecthomas/template
```
Verify that the installation is successful: swag -v
Annotate the controller that is the interface
```
// @Summary Get the list
// @Produce json
// @Param name query string false "name" maxlength(100)
// @Param state query int false "state" Enums(0, 1) default(1)
// @Param page query int false "page number"
// @Param page_size query int false "Number per page"
// @Success 200 {object} model.Tag "Success"
// @Failure 400 {object} code.Error "Request error"
// @Failure 500 {object} code.Error "Internal error"
// @Router /api/list [get]
func (c *Controller) List (c *gin.Context) {
app.Success(c, nil)
}
To distinguish items, add a comment to the main entry function:
// @title gin system
// @version 1.0
// @description gin developed system
// @termsOfService
func main(){}
Add in the model file
type ArticleSwagger struct {
List []*Article
Pager *app.Pager
}
```
Set the route, first in apiRouter.go (otherwise it will report: Failed to load spec)
```
import(
_ "ginpro/docs"
)
```
Set again
```
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
```
Generate swagger document: execute swag init in the root directory
swagger document view http://127.0.0.1:8001/swagger/index.html view
11. If you don’t need some of these components, such as es, redis, mongo, etc., you can comment out the relevant ones in the boot/boot.go init method
#### Instructions for use
1. After starting the project, we can see the corresponding routing information, which can be accessed using a browser or postman.
2. View link information: http://127.0.0.1:16686/
3. File upload test ```curl -X POST http://127.0.0.1:8000/upload/file -F file=@{file_path} -F type=1```
4. Visit after project launch http://127.0.0.1:8088/api/articles
5. The table creation statement is only a simple display at present, so only a simple table is created
```mysql
CREATE DATABASE blog;
USE blog;
CREATE TABLE `article` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`introduction` varchar(500) COLLATE utf8mb4_unicode_ci,
`views` int(11) NOT NULL DEFAULT '0',
`content` varchar(5000) COLLATE utf8mb4_unicode_ci,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=Innodb DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO blog.article VALUES(NULL, "My first article", "Article introduction", 100, "The content of the article is very good", "2020-02-02 02:22:22", "2020-02-02 02:22:22")
```