使用gin與gorm開發(fā)CRUD操作

gin啟動(dòng)

昨天學(xué)習(xí)到gin如何返回一個(gè)json數(shù)據(jù)之后,希望按照往常的開發(fā)經(jīng)驗(yàn),定義統(tǒng)一的返回報(bào)文體,于是定義了以下結(jié)構(gòu)

type BaseResponse struct {
    code    string
    message string
}

然而使用下面的代碼返回的數(shù)據(jù)一直是{}

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)
}

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

gin結(jié)合gorm

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

  • 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)
}

簡單地做了一個(gè)邏輯處理,發(fā)送post請(qǐng)求localhost:2046/author?AuthorName=xxx,然后在數(shù)據(jù)庫中新增一條author記錄,返回結(jié)果成功。

{
"Code": "000000",
"Message": "Create author with name : xxx"
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容