使用gin與gorm開發CRUD操作

gin啟動

昨天學習到gin如何返回一個json數據之后,希望按照往常的開發經驗,定義統一的返回報文體,于是定義了以下結構

type BaseResponse struct {
    code    string
    message string
}

然而使用下面的代碼返回的數據一直是{}

func main() {
    r := gin.Default()
    r.GET("/hello", hello)
    r.Run() // listen and serve on 0.0.0.0:8080
}

func hello(c *gin.Context) {
    res := &BaseResponse{
        code:    "000000",
        message: "hello world",
    }
    c.JSON(200, res)
}

自己研究源碼搗鼓半天也沒弄出來個所以然,于是查閱資料才知道犯了一個很基礎的錯誤。c.JSON方法底層使用了json.Marshal來序列化參數,這個方法只能序列化公有屬性,也就是說要把BaseResponse中字段的首字母大寫。首字母大寫表示公有可導出的,小寫是私有,這個知識點在GO中是比較基礎的,很多地方都會用到,需要牢記。

gin結合gorm

接下來就開始使用gorm來進行crud操作了。我在service.go文件中提供了數據庫連接的配置與初始化方法,在server.go文件中首先初始化數據庫連接,再啟動web容器接收請求。

  • server.go
type BaseResponse struct {
    Code    string
    Message string
}

func main() {
    ConfigDb("1", "2", "3", 4, "5")
    InitDb()
    defer Db.Close()

    r := gin.Default()
    r.POST("/author", addAuthor)
    r.Run("localhost:2046")
}

func addAuthor(c *gin.Context) {
    author := &Author{
        AuthorName: c.Query("AuthorName"),
        CreateTime: time.Now(),
    }
    NewAuthor(*author)
    message := fmt.Sprintf("Create author with name : %s", author.AuthorName)
    res := &BaseResponse{
        Code:    "000000",
        Message: message,
    }
    c.JSON(200, res)
}
  • service.go
type DBConfig struct {
    user, pw, host string
    port int
    dbName string
}

var config *DBConfig
var Db *gorm.DB

func ConfigDb(user, pw, host string, port int, dbName string) {
    config = &DBConfig{
        user:   user,
        pw:     pw,
        host:   host,
        port:   port,
        dbName: dbName,
    }
}

func InitDb() *gorm.DB {
    if config == nil {
        panic("Do configuration first!")
    }
    // connect to mysql
    connStr := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", config.user, config.pw, config.host, config.port, config.dbName)
    var err error
    Db, err = gorm.Open("mysql", connStr)
    if err != nil {
        panic("Connect to database fail")
    }
    Db.SingularTable(true)
    Db.LogMode(true)
    return Db
}

// crud
func NewAuthor(author Author) {
    Db.Create(&author)
}

簡單地做了一個邏輯處理,發送post請求localhost:2046/author?AuthorName=xxx,然后在數據庫中新增一條author記錄,返回結果成功。

{
"Code": "000000",
"Message": "Create author with name : xxx"
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。