從零開始學golang之gin加上gorm

freedbg發表於2018-01-18
package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "github.com/jinzhu/gorm"
    "time"
    //這裡我們匯入已經整合的 mysql 驅動,當然也可以匯入原版的 import _ "github.com/go-sql-driver/mysql" 一樣的
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

//step1 獲取 http_proxy=192.168.1.2:20080 go get github.com/gin-gonic/gin
//http_proxy=192.168.1.2:20080 這部分是代理設定
//
//step2 http_proxy=192.168.1.2:20080 go get -u github.com/jinzhu/gorm
//
//step3 http_proxy=192.168.1.2:20080 go get github.com/go-sql-driver/mysql
//
type User struct {
    ID        uint `gorm:"primary_key`
    Uname     string
    CreatedAt time.Time
}

func main() {
    r := gin.Default()
    v1 := r.Group("api/v1")
    {
        v1.GET("/users", GetUsers)
    }
    db, err := gorm.Open("mysql", "golang:Password&123@tcp(127.0.0.1:3306)/golang?charset=utf8&parseTime=True&loc=Local")
    defer db.Close()
    if err == nil {
        fmt.Println("DB connect success")
    }

    user := User{Uname: "test1"}
    fmt.Println(db.NewRecord(user)) // => returns `true` as primary key is blank

    ret := db.Create(&user)
    fmt.Println(user)
    fmt.Println(ret.Error)
    r.Run(":8080")

}

func GetUsers(c *gin.Context) {
    c.JSON(200, "helloman")
}

喜歡拉程式碼可以直接拉

https://github.com/godla/golang-gin-web-study.git

一起每天來寫一點吧

更多原創文章乾貨分享,請關注公眾號
  • 從零開始學golang之gin加上gorm
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章