When I run the app, I get the error “stderr: panic: runtime error: invalid memory address or nil pointer dereference”. This error occurs when I use the AutoMigrate function
Here is the simple example:
main.go
package main
import (
"testproject/controllers"
"testproject/initializers"
"github.com/gin-gonic/gin"
)
func init() {
initializers.LoadEnvVariables()
initializers.ConnectToDb()
initializers.SyncDatabase()
}
func main() {
r := gin.Default()
r.POST("/signup", controllers.Signup)
r.Run()
}
userModel.go
package models
import "gorm.io/gorm"
type User struct {
gorm.Model
Email string `gorm:"unique"`
Password string
}
syncDatabase.go
package initializers
import "testproject/models"
func SyncDatabase() {
GlobalDB.AutoMigrate(&models.User{})
}
thinking that this error is caused by the database, I created and tried different databases but I always encountered the same issue