Revised Question
I am trying to create a new user using Golang. I have a CreateUser()
function in my UserImplementation
struct which takes a pointer to a User
model. The function is responsible for creating a new user record in the database. However, when I try to run the function, I keep getting the error message "Nil pointer". Can someone help me figure out what I'm doing wrong?
Here is the code for my CreateUser()
function:
func (usr *UserImplementation) CreateUser(user *models.User) (*models.User, error) {
fmt.Println("User date", user.CreatedAt)
fmt.Println("User name", user.FirstName)
fmt.Println("User data", user.Password)
pg := databaseapi.NewApiConfig{}
params := database_utils.CreateUserParams{
ID: uuid.New(),
CreatedAt: time.Now().UTC(),
UpdatedAt: time.Now().UTC(),
FirstName: user.FirstName,
LastName: user.LastName,
OtherName: user.OtherName,
Password: user.Password,
Email: user.Email,
ProfileImage: user.ProfileImage,
Status: user.Status,
Username: user.Username,
IsAdmin: user.IsAdmin,
Role: user.Role,
Gender: user.Gender,
PhoneNumber: user.PhoneNumber,
}
userResponse, err := pg.ApiConfig.DB.CreateUser(usr.ctx, params)
if err != nil {
return nil, fmt.Errorf("error: %v", err.Error())
}
return (*models.User)(&userResponse), nil
}
I also have a UserController
struct that has a CreateUser()
function. Here is the code for that:
type UserController struct {
UserCtrl *usersimpl.UserImplementation
}
func (usrCtrl *UserController) CreateUser(ctx *gin.Context) {
var user models.User
if err := ctx.ShouldBindJSON(&user); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"Error": err.Error(),
})
return
}
_, err := utilities.EmailValidator(user.Email)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"Error": err.Error(),
})
return
}
hashPassword, err := utilities.HashPassword(user.Password)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"Error": err.Error(),
})
}
user.Password = hashPassword
resp, err := usrCtrl.UserCtrl.CreateUser(&user)
if err != nil {
ctx.JSON(
http.StatusBadRequest,
gin.H{
"Error": err.Error(),
},
)
return
}
ctx.JSON(http.StatusOK, gin.H{
"response": resp,
})
}
I've also created a UserImplementation
struct which has a NewUserService()
function. Here is the code for that:
type UserImplementation struct {
pg *database_utils.Queries
ctx context.Context
}
func NewUserService(pg *database_utils.Queries, ctx context.Context) *UserImplementation {
return &UserImplementation{
pg: pg,
ctx: ctx,
}
}
It is hard to say because you have provided only part of code. I think there can be two potential issues:
There are at least two ways to find the issue:
Hope it helps you to localise issue and find solution