In the below code my Register function is working well but the login function is showing an error with goroutines.
panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x2f0 pc=0x920427]
Please update me with a solution for this login, you can make a whole new login function just clear my concepts here.
var client *mongo.Client
func Register(c *fiber.Ctx) error {
var data map[string]string
if err := c.BodyParser(&data); err != nil {
return err
}
passwd, _ := bcrypt.GenerateFromPassword([]byte(data["password"]), 10)
user := models.User{
Name: data["name"],
Email: data["email"],
Password: passwd,
}
_, err := dao.UserData(&user)
if err != nil {
return c.JSON(err)
} else {
response := models.Response{
Message: "User Registered",
Success: true,
}
return c.JSON(response)
}
}
func Login(c *fiber.Ctx) error {
var data map[string]string
if err := c.BodyParser(&data); err != nil {
return err
}
var user models.User
var dbUser models.User
collection := client.Database("Shashank").Collection("User")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err := collection.FindOne(ctx, bson.M{"email": user.Email}).Decode(&dbUser)
if err != nil {
fmt.Println(fiber.StatusBadRequest)
} else {
fmt.Println(fiber.StatusOK)
}
if err := bcrypt.CompareHashAndPassword(user.Password, []byte(data["passwd"])); err != nil {
c.Status(fiber.StatusBadRequest)
return c.JSON(fiber.Map{
"message": "incorrect password",
})
}
return c.JSON(user)
}
CodePudding user response:
the first line in Login
func is var data map[string]string
that does not assign any memory - merely initializes variable data
to be of type map[string]string
. The zero value of map type is nil.
so in the next line when you do c.BodyParser(&data)
- &data
is trying to dereference a nil pointer - and hence your error.
change the first line to data := map[string]string{}
. Now there is a memory allocation and hence a valid memory that &data
can dereference.
CodePudding user response:
AFAIK maps usually have to be properly initialised with make()
. Try swapping
var data map[string]string
with
data := make(map[string]string)