本篇和 golang+gin+mysql构建RESTful API 篇理论上来说是没有本质的区别的。所不同的是,本篇将其代码进行了拆分成了,按mvc架构进行了重新划分。

一、安装依赖包

1go get github.com/go-sql-driver/mysql
2go get github.com/jinzhu/gorm
3go get github.com/gin-gonic/gin

二、建表语句

1CREATE TABLE `users` (
2  `id` bigint(20) NOT NULL AUTO_INCREMENT,
3  `username` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
4  `password` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
5  PRIMARY KEY (`id`)
6) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;

三、代码结构

 1├──api
 2│    ├── apis
 3│    │    └── user.go
 4│    ├── database
 5│    │    └── mysql.go
 6│    ├── models
 7│    │    └── user.go
 8│    └── router
 9│         └──  router.go
10└──main.go

四、源码

api/apis/user.go内容如下:

 1package apis
 2import (
 3    "github.com/gin-gonic/gin"
 4    model "api/models"
 5    "net/http"
 6    "strconv"
 7)
 8//列表数据
 9func Users(c *gin.Context) {
10    var user model.User
11    user.Username = c.Request.FormValue("username")
12    user.Password = c.Request.FormValue("password")
13    result, err := user.Users()
14    if err != nil {
15        c.JSON(http.StatusOK, gin.H{
16            "code":    -1,
17            "message": "抱歉未找到相关信息",
18        })
19        return
20    }
21    c.JSON(http.StatusOK, gin.H{
22        "code": 1,
23        "data":   result,
24    })
25}
26//添加数据
27func Store(c *gin.Context) {
28    var user model.User
29    user.Username = c.Request.FormValue("username")
30    user.Password = c.Request.FormValue("password")
31    id, err := user.Insert()
32    if err != nil {
33        c.JSON(http.StatusOK, gin.H{
34            "code":    -1,
35            "message": "添加失败",
36        })
37        return
38    }
39    c.JSON(http.StatusOK, gin.H{
40        "code":  1,
41        "message": "添加成功",
42        "data":    id,
43    })
44}
45//修改数据
46func Update(c *gin.Context) {
47    var user model.User
48    id, err := strconv.ParseInt(c.Param("id"), 10, 64)
49    user.Password = c.Request.FormValue("password")
50    result, err := user.Update(id)
51    if err != nil || result.ID == 0 {
52        c.JSON(http.StatusOK, gin.H{
53            "code":    -1,
54            "message": "修改失败",
55        })
56        return
57    }
58    c.JSON(http.StatusOK, gin.H{
59        "code":  1,
60        "message": "修改成功",
61    })
62}
63//删除数据
64func Destroy(c *gin.Context) {
65    var user model.User
66    id, err := strconv.ParseInt(c.Param("id"), 10, 64)
67    result, err := user.Destroy(id)
68    if err != nil || result.ID == 0 {
69        c.JSON(http.StatusOK, gin.H{
70            "code":    -1,
71            "message": "删除失败",
72        })
73        return
74    }
75    c.JSON(http.StatusOK, gin.H{
76        "code":  1,
77        "message": "删除成功",
78    })
79}

database/mysql.go内容

 1package database
 2import (
 3    _ "github.com/go-sql-driver/mysql" //加载mysql
 4    "github.com/jinzhu/gorm"
 5    "fmt"
 6)
 7var Eloquent *gorm.DB
 8func init() {
 9    var err error
10    Eloquent, err = gorm.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test?charset=utf8&parseTime=True&loc=Local&timeout=10ms")
11    if err != nil {
12        fmt.Printf("mysql connect error %v", err)
13    }
14    if Eloquent.Error != nil {
15        fmt.Printf("database error %v", Eloquent.Error)
16    }
17}

models/user.go

 1package models
 2    import (
 3        orm "api/database"
 4    )
 5    type User struct {
 6        ID       int64  `json:"id"`       // 列名为 `id`
 7        Username string `json:"username"` // 列名为 `username`
 8        Password string `json:"password"` // 列名为 `password`
 9    }
10    var Users []User
11    //添加
12    func (user User) Insert() (id int64, err error) {
13        //添加数据
14        result := orm.Eloquent.Create(&user)
15        id =user.ID
16        if result.Error != nil {
17            err = result.Error
18            return
19        }
20        return
21    }
22    //列表
23    func (user *User) Users() (users []User, err error) {
24        if err = orm.Eloquent.Find(&users).Error; err != nil {
25            return
26        }
27        return
28    }
29    //修改
30    func (user *User) Update(id int64) (updateUser User, err error) {
31        if err = orm.Eloquent.Select([]string{"id", "username"}).First(&updateUser, id).Error; err != nil {
32            return
33        }
34        //参数1:是要修改的数据
35        //参数2:是修改的数据
36        if err = orm.Eloquent.Model(&updateUser).Updates(&user).Error; err != nil {
37            return
38        }
39        return
40    }
41    //删除数据
42    func (user *User) Destroy(id int64) (Result User, err error) {
43        if err = orm.Eloquent.Select([]string{"id"}).First(&user, id).Error; err != nil {
44            return
45        }
46        if err = orm.Eloquent.Delete(&user).Error; err != nil {
47            return
48        }
49        Result = *user
50        return
51    }

router/router.go源码

 1package router
 2import (
 3    "github.com/gin-gonic/gin"
 4    . "api/apis"
 5)
 6func InitRouter() *gin.Engine {
 7    router := gin.Default()
 8    router.GET("/users", Users)
 9    router.POST("/user", Store)
10    router.PUT("/user/:id", Update)
11    router.DELETE("/user/:id", Destroy)
12    return router
13}

main.go源码

 1package main
 2import (
 3        _ "api/database"
 4        "api/router"
 5        orm "api/database"
 6 )
 7func main() {
 8        defer orm.Eloquent.Close()
 9        router := router.InitRouter()
10        router.Run(":8000")
11}

五、测试

执行 go run main.go,访问地址:

1POST localhost:8006/user 添加
2GET localhost:8006/users 列表
3DELETE localhost:8006/user/id 删除
4PUT localhost:8006/user/id 修改