Create a gin project from 0
build project
Project initialization operation
Create a new project folder, such as the demo folder. After the creation is complete, right-click the command line tool in the folder and enter
go init mod demo
demo can be customized, try to keep the name the same as the folder name.
因为
:
This step is to create the package management directory of go, and there will be a line at the top of the created mod fileThe module demo is as follows
module demo
The files in the project refer to each other need to get the location according to this module
引用方式如下
import "demo/项目下的文件夹名称"
Add the necessary library. This project requires
gin库:
the gin framework, which is mainly used to generate routes, route management, etc.
gorm库:
It is mainly used to simplify the operation of the database. It is used to
mysql库:
connect to the mysql database, etc.
viper库:
to parse the yaml file and read the configuration file.
Before installing these libraries, you can switch the package management mode of go to mod mode
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
Then install these libraries in the current folder as follows
//-u可以不加,-u是为了保证拉取最新的包
go get -u github.com/gin-gonic/gin
go get -u gorm.io/driver/mysql
go get -u gorm.io/gorm
go get -u github.com/spf13/viper
Create directory structure
According to the design pattern of mvc, create a folder directory
demo
│ README.md
│ main.go //入口文件
└───conf //基础配置,定义数据库名称密码等
│ │ conf.go
│ │ config.yaml
└───models // domain+dao层 - models文件夹,定义实体类,查询数据库。
│ │ initDB.go
└───routers // controller层 - routers文件夹,主要执行与前端的api的映射,调用service层的方法
│ │ router.go //初始化router操作等
│ └───api //api文件夹下分类接口所属模块
└───service //service层 - service文件夹,主要对获取到的数据执行逻辑上的处理,并且返回到controller层
│ │ xxx.go
└───logs //用来存储logs记录
Project details see https://github.com/jiangbo66666/gin-vue-microBlog
The project is committed to making a social tool similar to Weibo, and it is only initializing now, to be continued. . . .