Golang中gorm+gin的简单使用

小小程序员Eric · · 3549 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

自己做记录,方便查看

    package main
    
    import (
        "fmt"
        "github.com/gin-gonic/gin"
        _ "github.com/go-sql-driver/mysql"
        "github.com/jinzhu/gorm"
    )
    
    type User struct {
        Id       int    `json:"id",gorm:"auto-increment"`
        Name     string `json:"name"`
        Tel      string `json:"tel"`
        Password string `json:"password"`
    }
    
    type ResponseData struct {
        Code    int         `json:"code"`
        Status  string      `json:"status"`
        Message string      `json:"message"`
        Data    interface{} `json:"data"`
    }
    
    var db *gorm.DB
    var err error
    
    func main() {
        // db
        db, err = gorm.Open("mysql", "root:03140314@/golang_test?charset=utf8&parseTime=True&loc=Local")
        checkErr()
        //db.SingularTable(true)
        db.AutoMigrate(&User{})
        defer db.Close()
        // http
        router := gin.Default()
        v1 := router.Group("/api/v1")
        {
            // user
            v1.POST("/user/login", login)
            v1.POST("/user/register", register)
            v1.GET("/user/get_info", getUserInfo)
        }
        router.Run()
    }
    
    func checkErr() {
        if err != nil {
            fmt.Println(err)
            err = nil
        }
    }
    
    // post form
    func login(c *gin.Context) {
        // 获取表单数据 tel,password
        tel := c.PostForm("tel")
        psd := c.PostForm("password")
        if len(tel) == 0 || len(psd) == 0 {
            response := ResponseData{
                Code:    50001,
                Status:  "error",
                Message: "账号或密码不能为空",
                Data:    "",
            }
            c.JSON(200, response)
        } else {
            var user User
            db.Where("tel=?", tel).First(&user)
            if user.Tel == "" {
                response := ResponseData{
                    Code:    50001,
                    Status:  "error",
                    Message: "用户不存在",
                    Data:    "",
                }
                c.JSON(200, response)
            } else {
                if user.Password == psd {
                    response := ResponseData{
                        Code:    200,
                        Status:  "success",
                        Message: "登录成功",
                        Data:    "",
                    }
                    c.JSON(200, response)
                } else {
                    response := ResponseData{
                        Code:    5001,
                        Status:  "error",
                        Message: "密码错误",
                        Data:    "",
                    }
                    c.JSON(200, response)
                }
            }
        }
    }
    
    // post form
    func register(c *gin.Context) {
        tel := c.PostForm("tel")
        psd := c.PostForm("password")
        if len(tel) == 0 || len(psd) == 0 {
            response := ResponseData{
                Code:    50001,
                Status:  "error",
                Message: "账号或密码不能为空",
                Data:    "",
            }
            c.JSON(200, response)
            return
        }
        var user User
        db.Where("tel=?", tel).First(&user)
        if user.Tel == tel {
            response := ResponseData{
                Code:    50001,
                Status:  "error",
                Message: "手机号已注册",
                Data:    "",
            }
            c.JSON(200, response)
        } else {
            newUser := User{Tel: tel, Password: psd}
            db.Create(&newUser)
            response := ResponseData{
                Code:    200,
                Status:  "success",
                Message: "注册成功",
                Data:    "",
            }
            c.JSON(200, response)
        }
    }
    
    // get url
    func getUserInfo(c *gin.Context) {
        id := c.Query("id")
        if id == "" {
            response := ResponseData{
                Code:    50001,
                Status:  "error",
                Message: "参数错误",
                Data:    "",
            }
            c.JSON(200, response)
            return
        }
        var user User
        db.First(&user, id)
        if user.Id > 0 {
            response := ResponseData{
                Code:    200,
                Status:  "success",
                Message: "",
                Data:    user,
            }
            c.JSON(200, response)
        } else {
            response := ResponseData{
                Code:    50001,
                Status:  "error",
                Message: "用户不存在",
                Data:    "",
            }
            c.JSON(200, response)
        }
    }

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:小小程序员Eric

查看原文:Golang中gorm+gin的简单使用

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

3549 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传