1.gin-gorm项目初始化

2023-02-13 00:00:01

技术


通过gin-gorm之项目学习部分的学习,可以对项目的架构有深入的了解 🤟 {% post_link "gin-gorm1项目准备初始化" %}
{% post_link "gin-gorm2数据库" %}
{% post_link "gin-gorm3错误处理与路由接口" %}
{% post_link "gin-gorm4用户模块接口编写" %}
{% post_link "gin-gorm5密码加密" %}
{% post_link "gin-gorm6编辑、删除用户" %}


顺便说一下hexo中如何做文章跳转,例如上面的目录第一项在 md 中要这么写: {% post_link "gin-gorm1项目准备初始化" %}<br/> "gin-gorm1项目准备初始化"是 md 文件的名字,而不是 md 中 format 的 title 的名称,显示时会显示 title 的名称

一、创建仓库

GitHub 创建项目仓库,git clone拉取项目

二、初始化

创建main.go文件,在项目根目录下执行

go mod init <项目名> 

三、安装gin

gin 官方文档 下载安装:在项目根目录下执行

go get -u github.com/gin-gonic/gin

四、搭建项目结构

gin是灵活的web框架,不会限制我们的项目结构,所以需要我们自己去建立

项目结构如下:

config 网站配置、参数等等  
model 数据,读写  
api(controller) 前后端接口  
middleware 中间件,登录验证、跨域等等  
routes 路由接口  
utils 工具包,实现公用的功能  
upload 上传下载,托管静态资源  
web 前端页面托管  

五、网站配置参数

可以在config文件夹下新建config.go文件,在其中写基本配置参数

不过此处使用go ini来进行配置 安装go ini,在根目录下执行

go get gopkg.in/ini.v1

在config文件夹下新建config.ini文件,在其中写网站的基本配置参数 ini写法:

# 注释
[分区]
key=value

配置如下

[server]
AppMode=debug
HttpPort=:3000

[database]
Db=postgresql
DbHost=localhost
DbPort=5432
DbUser=postgres
DbPassword=123456
DbName=ginblog

在utils下新建setting.go,将config.ini的参数引入并作为全局变量

var (
    AppMode  string
    HttpPort string

    Db         string
    DbHost     string
    DbPort     string
    DbUser     string
    DbPassword string
    DbName     string
)

func init() {
    file, err := ini.Load("../config/config.ini")
    if err != nil {
        fmt.Println("配置文件读取错误,请检查文件路径:", err)
    }
    loadServer(file)
    loadData(file)
}
//加载server配置
func loadServer(file *ini.File) {
    AppMode = file.Section("server").Key("AppMode").MustString("debug")
    HttpPort = file.Section("server").Key("HttpPort").MustString(":3000")
}
//加载database配置
func loadData(file *ini.File) {
    Db = file.Section("database").Key("Db").MustString("postgresql")
    DbHost = file.Section("database").Key("DbHost").MustString("localhost")
    DbPort = file.Section("database").Key("DbPort").MustString("5432")
    DbUser = file.Section("database").Key("DbUser").MustString("postgres")
    DbPassword = file.Section("database").Key("DbPassword").MustString("123456")
    DbName = file.Section("database").Key("DbName").MustString("ginblog")
}

在使用配置参数时调用setting.go,这样做是为了将配置参数抽离出来,当需要更改时只需要更改ini配置文件里面的配置

六、路由

在routes文件夹下建立router.go文件,作为路由入口文件

func InitRouter() {
    gin.SetMode(utils.AppMode)
    r := gin.Default()

    router := r.Group("api/v1")
    {
        router.GET("hello", func(ctx *gin.Context) {
            ctx.JSON(http.StatusOK, gin.H{
                "msg": "ok",
            })
        })

    }

    r.Run(utils.HttpPort)
}

在main中使用

func main() {
    routes.InitRouter()
}

测试

运行main.go 控制台打印

[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    /api/v1/hello             --> gin-vue-blog/routes.InitRouter.func1 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :3000

浏览器访问 localhost:3000/api/v1/hello 页面显示

{"msg":"ok"}

OK,一切正常