go get -u gorm.io/driver/sqlite
go get -u gorm.io/gorm
go get gorm.io/driver/mysql
如下生成article的一张表 (models/articles)
package models
import (
"gorm.io/gorm"
)
// 数据库表结构
type Article struct {
gorm.Model // 会引入4个字段(ID,创建于,修改于,删除于),删除为软删除
Id uint `gorm:"primary_key"`
Title string
Author string
Category string //demo就这么搞了,应该关联另一个类别表
Content string
}
// 数据库访问方法(比如增删改查CRUD)
// ...more
func initDB(){
//1. sqlite
db, err = gorm.Open(sqlite.Open("database/test.db"), &gorm.Config{})
//2. 连接Mysql数据库
//db, err = gorm.Open(mysql.Open(
// "root:pass@tcp(127.0.0.1:3306)/gincms?charset=utf8mb4&parseTime=True&loc=Local"),
// &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Migrate the schema
db.AutoMigrate(&Article{})
// 插入内容
// db.Create(&Article{Title: "测试标题1", Author: "作者1", Content: "1000"})
// db.Create(&Article{Title: "测试标题2", Author: "作者2", Content: "3500"})
}
routers/router.go
func InitRouters() *gin.Engine {
router := gin.Default()
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
// 路由分组
r:= router.Group("/api")
r.GET("/", withMain)
// 文章crud
r.GET("/article", handlers.GetArticle)
r.DELETE("/article", handlers.DeleteArticle)
r.POST("/article", handlers.AddArticle)
r.PUT("/article", handlers.EditArticle)
return router
}
func withMain(c *gin.Context) {
c.JSON(200, gin.H{
"main": "this is a main page"
})
}
...more
IN package handles
// @Summary 删除文章
// @Tags 文章
// @Produce json
// @Param id query string true "id"
// @Success 200 {string} json "{"code":200,"data":[],"message":"ok"}"
// @Router /api/article [delete]
func DeleteArticle(context *gin.Context) {
id := context.DefaultQuery("id", "null")
statusOK,_ := models.DeleteArticleById(id)
context.Set("result",If(statusOK,"成功","失败"))
}
IN package models:
func DeleteArticleById(id string) (bool, error) {
err := db.Where("id = ?", id).Delete(&Article{}).Error
if err != nil && err != gorm.ErrRecordNotFound {
return false, err
}
return true, nil
}
类似于前端webpack保存时的热更新,go也有一大堆热重载工具
set GOOS=linux
set GOARCH=amd64
go build main.go
for key, value := range oldMap {
newMap[key] = value
}
var db *gorm.DB
func xxx(){
db = ........
// 用成db:= ......,,,就gerp了,还是不太熟悉
}