您的位置:首页 > Gin博客配置文件使用全解析
发布于2025-08-13 阅读(0)
扫一扫,手机访问
以下是关于Gin框架的初始化和配置文件使用指南的伪原创版本,保持了原文的大意和语言,同时调整了部分表达方式。
Gin 框架的官方文档可以在 这里 找到。
要初始化一个 Gin 项目,首先需要设置 Go 模块代理:
GOPROXY=https://goproxy.cn,direct
然后初始化项目:
go mod init projectName
配置并构建项目:
go build

通过以下命令安装 Gin:
go get -u github.com/gin-gonic/gin
-u 标志表示如果已存在 Gin,则更新到最新版本。
Gin 项目的目录结构如下:

我们选择使用 .ini 文件作为网站的配置文件。相关文档可以在 这里 找到。
安装所需的包:
go get gopkg.in/ini.v1
在项目根目录下创建 config/config.ini 文件。.ini 文件的结构包括分区、键和值。
config/config.ini
[server] AppMode = debug HttpPort = :3000 [database] Db = mysql Dbhost = localhost DbUser = DbPassWord = DbName = ginVue3blog
在 utils 目录中读取配置文件数据,并声明配置文件中的全局变量。
安装所需的包:
go get -u gopkg.in/ini.v1
详细参考文档:这里
utils/setting
package utils
import (
"fmt"
"gopkg.in/ini.v1"
)
var (
AppMode string
HttpPort string
Db string
DbHost string
DbPort string
DbUser string
DbPassWord string
DbName string
)
func init() {
cfg, err := ini.Load("../config/config.ini")
if err != nil {
fmt.Printf("无法读取文件: %v", err)
}
AppMode = cfg.Section("server").Key("AppMode").MustString("debug")
HttpPort = cfg.Section("server").Key("HttpPort").MustString("debug")
Db = cfg.Section("database").Key("Db").MustString("mysql")
DbHost = cfg.Section("database").Key("DbHost").MustString("localhost")
DbPort = cfg.Section("database").Key("Db Port").MustString("3306")
DbUser = cfg.Section("database").Key("DbUser").MustString("root")
DbPassWord = cfg.Section("database").Key("DbPassWord").MustString("wucs123")
DbName = cfg.Section("database").Key("DbName").MustString("ginVue3blog")
}routes/router
package routes
import (
setting "ginVue3blog/utils"
"github.com/gin-gonic/gin"
"net/http"
)
func InitRouter() {
gin.SetMode(setting.AppMode)
r := gin.Default()
router := r.Group("api/v1")
{
router.GET("hello", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"msg": "ok",
})
})
}
// 此函数可以返回一个引擎 *gin.Engine,然后在 main 函数中调用运行
// 也可以不返回,直接运行
r.Run(setting.HttpPort)
}main.go
package main
import "ginVue3blog/routes"
func main() {
// 引入路由
routes.InitRouter()
}
图片及部分相关技术知识点来源于网络搜索,如有侵权请联系删除!
下一篇:黑暗战士搭配哪个职业好?
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
4
5
6
7
8
9