补充程序配置
This commit is contained in:
parent
5c9c08013a
commit
46e6929f52
@ -22,4 +22,24 @@
|
||||
|
||||
## 项目准备
|
||||
|
||||

|
||||

|
||||
|
||||
|
||||
## v2 版本
|
||||
|
||||
```go
|
||||
// 初始化数据库, 能过与数据库交互的 连接池对象: db
|
||||
func setupDatabase() *gorm.DB {
|
||||
dsn := "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
panic("failed to connect database")
|
||||
}
|
||||
db.AutoMigrate(&Book{}) // 自动迁移
|
||||
return db.Debug()
|
||||
}
|
||||
```
|
||||
|
||||
### 剥离配置
|
||||
|
||||
剥离程序配置,让程序可以通过外部加载配置: config 包: 用来管理程序的配置
|
||||
|
37
book/config/config.go
Normal file
37
book/config/config.go
Normal file
@ -0,0 +1,37 @@
|
||||
package config
|
||||
|
||||
// 定义程序配置
|
||||
// dsn := "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
// 凡是可以提出出配置的
|
||||
|
||||
// 程序的配置对象
|
||||
type Config struct {
|
||||
App `json:"app"`
|
||||
MySQL `json:"mysql"`
|
||||
}
|
||||
|
||||
// app:
|
||||
//
|
||||
// host: 127.0.0.1
|
||||
// port: 8080
|
||||
type App struct {
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
}
|
||||
|
||||
// mysql:
|
||||
//
|
||||
// host: 127.0.0.1
|
||||
// port: 3306
|
||||
// database: test
|
||||
// username: "root"
|
||||
// password: "123456"
|
||||
// debug: true
|
||||
type MySQL struct {
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
Database string `json:"database"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Debug bool `json:"debug"`
|
||||
}
|
5
book/config/load.go
Normal file
5
book/config/load.go
Normal file
@ -0,0 +1,5 @@
|
||||
package config
|
||||
|
||||
// 配置的加载
|
||||
|
||||
// 程序的其他的部分如何读写程序配置
|
@ -18,7 +18,7 @@ func setupDatabase() *gorm.DB {
|
||||
panic("failed to connect database")
|
||||
}
|
||||
db.AutoMigrate(&Book{}) // 自动迁移
|
||||
return db
|
||||
return db.Debug()
|
||||
}
|
||||
|
||||
func Failed(ctx *gin.Context, err error) {
|
||||
@ -52,6 +52,7 @@ func main() {
|
||||
ctx.JSON(http.StatusOK, ins)
|
||||
})
|
||||
// 查询Book列表 -> []*Book
|
||||
// SELECT * FROM `books`
|
||||
book.GET("", func(ctx *gin.Context) {
|
||||
var books []Book
|
||||
if err := db.Find(&books).Error; err != nil {
|
||||
|
Loading…
x
Reference in New Issue
Block a user