Я пытаюсь обновить пользователей в mysql БД, и я получаю сообщение об ошибке runtime error: invalid memory address or nil pointer dereference
Я не уверен, в чем проблема
мой запрос
queryUpdateUser = "UPDATE users SET firstName=?, lastName=?, email=? WHERE id=?;"
мой DAO
func (user *User) Update() *errors.Error {
stmt, err := usersdb.Client.Prepare(queryUpdateUser)
if err != nil {
return errors.NewInteralServerError(err.Error())
}
defer stmt.Close()
user.UpdatedAt = dates.GetNowString()
_, err = stmt.Exec(user.FirstName, user.LastName, user.Email)
if err != nil {
return errors.ParseError(err)
}
return nil
}
UserService
func GetUser(userId int64) (*users.User, *errors.Error) {
result := &users.User{Id: userId}
if err := result.Get(); err != nil {
return nil, err
}
return result, nil
}
func UpdateUser(user users.User) (*users.User, *errors.Error) {
current, err := GetUser(user.Id)
if err != nil {
return nil, err
}
fmt.Println(current)
current.FirstName = user.FirstName
current.LastName = user.LastName
current.Email = user.Email
current.UpdatedAt = dates.GetNowString()
fmt.Println(current)
if err := current.Update(); err != nil {
return nil, err
}
return current, nil
}
мой контроллер
func UpdateUser(c *gin.Context) {
userId, userErr := strconv.ParseInt(c.Param("user_id"), 10, 64)
if userErr != nil {
err := errors.NewBadRequestError("invalid user id")
c.JSON(err.Status, err)
return
}
var user users.User
if err := c.ShouldBindJSON(&user); err != nil {
// TODO: hnadle json error return bad request
err := errors.NewBadRequestError("invalid json body")
c.JSON(err.Status, err)
// fmt.Println(err.Error())
return
}
user.Id = userId
result, err := services.UpdateUser(user)
if err != nil {
// TODO: handle user updating error
c.JSON(err.Status, err)
return
}
c.JSON(http.StatusOK, result)
}
добавлено usersdb
var (
Client *sql.DB
)
func init() {
loadErr := godotenv.Load()
if loadErr != nil {
log.Fatal("Error loading .env file")
}
host := os.Getenv("DB_HOST")
driver := os.Getenv("DB_DRIVER")
user := os.Getenv("DB_USER")
password := os.Getenv("DB_PASSWORD")
name := os.Getenv("DB_NAME")
port := os.Getenv("DB_PORT")
datasourceName := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", user, password, host+":"+port, name,)
fmt.Println("%s:%s@tcp(%s)/%s?charset=utf8", user, password, host+":"+port, name)
// fmt.print("%s:%s@tcp(%s)/%s?charset=utf8", user, password, host+port, name)
var err error
Client, err = sql.Open(driver, datasourceName)
if err != nil {
panic(err)
}
if err = Client.Ping(); err != nil {
panic(err)
}
log.Println("DB successfully configured")
}
STACK TRACE
runtime error: invalid memory address or nil pointer dereference /usr/local/Cellar/go/1.13.6/libexec/src/runtime/panic.go:199 (0x104446b)
panicmem: panic(memoryError) /usr/local/Cellar/go/1.13.6/libexec/src/runtime/signal_unix.go:394 (0x10442a8)
sigpanic: panicmem() /Users/Olar/Documents/Dev/Go/bookstore_users-api/utils/errors/MysqlError.go:16 (0x1564727)
ParseError: sqlErr, ok := err.(*mysql.MySQLError) /Users/Olar/Documents/Dev/Go/bookstore_users-api/utils/errors/MysqlError.go:18 (0x15647fa)
ParseError: if strings.Contains(sqlErr.Error(), errorNowRows) { /Users/Olar/Documents/Dev/Go/bookstore_users-api/domain/users/UserDao.go:77 (0x1565405)
(*User).Update: return errors.ParseError(err) /Users/Olar/Documents/Dev/Go/bookstore_users-api/services/UsersService.go:47 (0x15b7955)
UpdateUser: if err := current.Update(); err != nil { /Users/Olar/Documents/Dev/Go/bookstore_users-api/controllers/users/UsersController.go:80 (0x15b82cd)
UpdateUser: result, err := services.UpdateUser(user) /Users/Olar/home/golib/pkg/mod/github.com/gin-gonic/gin@v1.5.0/context.go:147 (0x14f425a)
(*Context).Next: c.handlers[c.index](c) /Users/Olar/home/golib/pkg/mod/github.com/gin-gonic/gin@v1.5.0/recovery.go:83 (0x1507cf3)
RecoveryWithWriter.func1: c.Next() /Users/Olar/home/golib/pkg/mod/github.com/gin-gonic/gin@v1.5.0/context.go:147 (0x14f425a)
(*Context).Next: c.handlers[c.index](c) /Users/Olar/home/golib/pkg/mod/github.com/gin-gonic/gin@v1.5.0/logger.go:241 (0x1506e20)
LoggerWithConfig.func1: c.Next() /Users/Olar/home/golib/pkg/mod/github.com/gin-gonic/gin@v1.5.0/context.go:147 (0x14f425a)
(*Context).Next: c.handlers[c.index](c) /Users/Olar/home/golib/pkg/mod/github.com/gin-gonic/gin@v1.5.0/gin.go:403 (0x14fe289)
(*Engine).handleHTTPRequest: c.Next() /Users/Olar/home/golib/pkg/mod/github.com/gin-gonic/gin@v1.5.0/gin.go:364 (0x14fd97d)
(*Engine).ServeHTTP: engine.handleHTTPRequest(c) /usr/local/Cellar/go/1.13.6/libexec/src/net/http/server.go:2802 (0x12ce7c3)
serverHandler.ServeHTTP: handler.ServeHTTP(rw, req) /usr/local/Cellar/go/1.13.6/libexec/src/net/http/server.go:1890 (0x12ca064)
(*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req) /usr/local/Cellar/go/1.13.6/libexec/src/runtime/asm_amd64.s:1357 (0x105c4d0)
goexit: BYTE $0x90 // NOP
Ошибка sql:
"sql: expected 4 arguments, got 3"
Я не могу найти причину этой ошибки. Любая помощь приветствуется.