The Seven Year Itch.

MENU

Golang之gorm的操作使用

January 8, 2019 • Read: 102 • Go

下载需要用到的驱动,和第三方下载方式一律用 go get xxxx 来下载安装即可!

链接数据库这里会采坑

错误示例:

root:123123@192.168.3.30:3307/go?parseTime=True`

正确配置:

root:123123@(192.168.3.30:3307)/go?parseTime=True

package main

import (
    "encoding/json"
    _ "github.com/go-sql-driver/mysql"
    "github.com/gorilla/mux"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
    "log"
    "net/http"
)

var db *gorm.DB

var err error

type User struct {
    gorm.Model
    Name  string
    Email string
}

type Res struct {
    Message   string `json:"message"`
    ErrorCode int64  `json:"error_code"`
}

//type Ress []Res   如果使用 返回格式为: [{"message":"xx","error_code":0}]

func UserList(w http.ResponseWriter, r *http.Request) {
    db, err = gorm.Open("mysql", "root:leto123456@(192.168.3.30:3307)/go?parseTime=True")
    if err != nil {
        panic("Could not connect to the database")
    }

    defer db.Close()

    var users []User
    db.Find(&users)
    json.NewEncoder(w).Encode(users)
}

func UserAdd(w http.ResponseWriter, r *http.Request) {
    db, err = gorm.Open("mysql", "root:leto123456@(192.168.3.30:3307)/go?parseTime=True")
    if err != nil {
        panic("Could not connect to the database")
    }
    user := User{Name: "Jinzhu", Email: "xxx@email.com"}

    db.NewRecord(user) // => 主键为空返回`true`

    db.Create(&user)

    db.NewRecord(user) // => 创建`user`后返回`false`

    data := Res{Message: "创建用户成功!", ErrorCode: 0}

    json.NewEncoder(w).Encode(data)
}

func UserDetail(w http.ResponseWriter, r *http.Request) {
    db, err := gorm.Open("mysql", "root:leto123456@(192.168.3.30:3307)/go?parseTime=True")
    if err != nil {
        panic("Could not connect to the database")
    }
    defer db.Close()

    vars := mux.Vars(r)
    id := vars["id"]
    user := User{}
    db.First(&user, id)
    json.NewEncoder(w).Encode(user)
}

func UserDelete(w http.ResponseWriter, r *http.Request) {
    db, err := gorm.Open("mysql", "root:leto123456@(192.168.3.30:3307)/go?parseTime=True")
    if err != nil {
        panic("Could not connect to the database")
    }
    defer db.Close()
    vars := mux.Vars(r)
    id := vars["id"]
    db.Delete(&User{}, id)
    data := Res{Message: "删除成功!", ErrorCode: 0}
    json.NewEncoder(w).Encode(data)
}

func InitRouter() {
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/user/list", UserList).Methods("GET")
    myRouter.HandleFunc("/user/add", UserAdd).Methods("POST")
    myRouter.HandleFunc("/user/detail/{id}", UserDetail).Methods("GET")
    myRouter.HandleFunc("/user/delete/{id}", UserDelete).Methods("DELETE")
    log.Fatal(http.ListenAndServe(":8081", myRouter))
}

func main() {
    InitRouter()

}

Tags: None
Archives QR Code
QR Code for this page
Tipping QR Code