diff --git a/book/README.md b/book/README.md index 41f84a8..8816ed2 100644 --- a/book/README.md +++ b/book/README.md @@ -22,4 +22,24 @@ ## 项目准备 -![alt text](image.png) \ No newline at end of file +![alt text](image.png) + + +## 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 包: 用来管理程序的配置 diff --git a/book/config/config.go b/book/config/config.go new file mode 100644 index 0000000..0342c6f --- /dev/null +++ b/book/config/config.go @@ -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"` +} diff --git a/book/config/load.go b/book/config/load.go new file mode 100644 index 0000000..2c022e3 --- /dev/null +++ b/book/config/load.go @@ -0,0 +1,5 @@ +package config + +// 配置的加载 + +// 程序的其他的部分如何读写程序配置 diff --git a/skills/gin/main.go b/skills/gin/main.go index 2545e39..a10d15a 100644 --- a/skills/gin/main.go +++ b/skills/gin/main.go @@ -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 {