写一个注册接口遇到的空指针疑问

请问为何会报空指针的错误?

Code:

package main

import (
    "math/rand"
    "net/http"
    "time"

    "github.com/gin-gonic/gin"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

type User struct {
    *gorm.Model
    Name   string `gorm:"type:varchar(20);not null"`
    Phone  string `gorm:"type:varchar(11);unique;not null"`
    Passwd string `gorm:"size:255;not null"`
}

func main() {
    DB := InitDB()
    app := gin.Default()

    app.GET("api/v1/register", func(ctx *gin.Context) {
        name := ctx.PostForm("name")
        phone := ctx.PostForm("phone")
        passwd := ctx.PostForm("passwd")

        // 检查 phone
        if len(phone) == 11 {
            if IsPhoneExist(DB, phone) {
                ctx.JSON(http.StatusUnprocessableEntity, gin.H{
                    "msg": "user exist",
                })
                return
            }
        }

        // 检查 name
        if len(name) == 0 {
            name := RandomName(10)
            DB.Create(&User{Name: name, Phone: phone, Passwd: passwd})
            ctx.JSON(http.StatusOK, gin.H{
                "msg": "register success",
            })
            return
        }

    })

    app.Run(":80")

}

// 号码是否存在
func IsPhoneExist(DB *gorm.DB, phone string) bool {
    var user User
    DB.Where("phone = ?", phone).First(&user)

    if user.ID != 0 {
        return true
    }
    return false
}

// 空名称则随即生成一个
func RandomName(n int) string {
    letters := []byte("asdfghjklQWERTYUIOP")
    name := make([]byte, n)

    rand.Seed(time.Now().Unix())
    for i := range name {
        name[i] = letters[rand.Intn(len(letters))]
    }
    return string(name)
}

// Init 数据库
func InitDB() (DB *gorm.DB) {
    DSN := "root:123456..@tcp(127.0.0.1:3306)/gorm?charset=utf8mb4&parseTime=True&loc=Local"
    DB, _ = gorm.Open(mysql.Open(DSN))
    DB.AutoMigrate(&User{})
    return
}

Error:

2022/12/23 21:24:52 /Users/tom/go/src/Learn/main.go:67 record not found
[2.519ms] [rows:0] SELECT * FROM `users` WHERE phone = '13888888888' AND `users`.`deleted_at` IS NULL ORDER BY `users`.`id` LIMIT 1


2022/12/23 21:24:52 [Recovery] 2022/12/23 - 21:24:52 panic recovered:
GET /api/v1/register HTTP/1.1
Host: localhost
Accept: */*
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 389
Content-Type: multipart/form-data; boundary=--------------------------462561745692434217366880
Postman-Token: 81959ddb-4e76-449b-9412-3f7d20101178
User-Agent: PostmanRuntime/7.29.2


runtime error: invalid memory address or nil pointer dereference
/usr/local/Cellar/go/1.18.4/libexec/src/runtime/panic.go:220 (0x104a4f5)
        panicmem: panic(memoryError)
/usr/local/Cellar/go/1.18.4/libexec/src/runtime/signal_unix.go:818 (0x104a4c5)
        sigpanic: panicmem()
/Users/tom/go/src/Learn/main.go:69 (0x15500a5)
        IsPhoneExist: if user.ID != 0 {
/Users/tom/go/src/Learn/main.go:38 (0x154fd64)
        main.func1: if IsPhoneExist(DB, phone) {
/Users/tom/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0x148c861)
        (*Context).Next: c.handlers[c.index](c)
/Users/tom/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/recovery.go:101 (0x148c84c)
        CustomRecoveryWithWriter.func1: c.Next()
/Users/tom/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0x148b946)
        (*Context).Next: c.handlers[c.index](c)
/Users/tom/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/logger.go:240 (0x148b929)
        LoggerWithConfig.func1: c.Next()
/Users/tom/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0x148aa10)
        (*Context).Next: c.handlers[c.index](c)
/Users/tom/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/gin.go:616 (0x148a678)
        (*Engine).handleHTTPRequest: c.Next()
/Users/tom/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/gin.go:572 (0x148a1bc)
        (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/local/Cellar/go/1.18.4/libexec/src/net/http/server.go:2916 (0x129149a)
        serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/local/Cellar/go/1.18.4/libexec/src/net/http/server.go:1966 (0x128c496)
最佳答案

gorm判断数据是否存在,先用error判断。这里报错是gorm判断没对

1年前 评论
讨论数量: 3

没有报错信息,看不出来什么问题。

1年前 评论
Scrooge (楼主) 1年前

gorm判断数据是否存在,先用error判断。这里报错是gorm判断没对

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!