参考视频:【评论送书】Go语言 Gin+Vue 前后端分离实战 - OceanLearn_哔哩哔哩_bilibili
上一篇:(15条消息) Gin+Gorm+PostGresSQL+Vue项目实战(5)_代码骑士的博客-CSDN博客
一、通过config组件从文件中读取配置
下载config组件
go get github.com/spf13/viper
创建config文件夹,并创建子文件application.yml文件
·application.yml
这里是对数据库的一个配置项,通过调用函数可以直接读取这些配置,因为我们数据库已经连接过了,所以暂时先不用这些配置也是可以的。
server:
port: 1016
datasource:
driverName: postgres
host: 127.0.0.1
port: 5432
database: db2
username: postgres
password: 123456
database.go文件的一些修改(为了更好的读取配置文件并使用其参数,所以将数据库的连接方式进行了更改,如下所示:)
package common
import (
"fmt"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/spf13/viper"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
//"gorm.io/gorm"
)
var DB *gorm.DB
//数据库初始化
func InitDB() *gorm.DB {
//连接数据库
host := viper.GetString("datasource.host")
port := viper.GetString("datasource.port")
user := viper.GetString("datasource.username")
password := viper.GetString("datasource.password")
dbname := viper.GetString("datasource.database")
psqlInfo := fmt.Sprintf("host=%s port=%s user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := gorm.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
DB = db
return db
}
//获取数据库实例
func GetDB() *gorm.DB {
return DB
}
main.go文件修改(主要增添了一个初始化配置的一个函数并且调用配置文件中的监听端口):
package main
import (
"os"
"testGinAndVue01/common"
"testGinAndVue01/router"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/spf13/viper"
"github.com/gin-gonic/gin"
)
func main() {
InitConfig()
db := common.InitDB()
defer db.Close()
r := gin.Default()
r = router.CollectRoute(r)
port := viper.GetString("server.port")
if port != "" {
panic(r.Run(":" + port))
} else {
panic(r.Run())
}
}
func InitConfig() {
workDir, _ := os.Getwd()
viper.SetConfigName("application")
viper.SetConfigType("yml")
viper.AddConfigPath(workDir + "/config")
err := viper.ReadInConfig()
if err != nil {
return
}
}
进行监听端口1016测试:
请求:
后端:
继续使用我们的默认端口只需要在application.yml文件中删除server端口号即可。
server:
datasource:
driverName: postgres
host: 127.0.0.1
port: 5432
database: db2
username: postgres
password: 123456
执行后可以看到监听端口为8080:
下一篇: