0

im really new to go-lang, and want to take step further with unit tests, however i cant find any reference i want and still dont have any idea to perform it in this func :

func Login() gin.HandlerFunc {
return func(c *gin.Context) {
    var ctx, cancel = context.WithTimeout(context.Background(), 100*time.Second)
    defer cancel()
    var user models.User
    var foundUser models.User
    if err := c.BindJSON(&user); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    err := userFindOneCollection.FindOne(ctx, bson.M{"email": user.Email}).Decode(&foundUser)
    defer cancel()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "email or password is incorrect"})
        return
    }

    passwordIsValid, msg := VerifyPassword(*user.Password, *foundUser.Password)
    defer cancel()
    if !passwordIsValid {
        c.JSON(http.StatusInternalServerError, gin.H{"Error": msg})
        return
    }

    if foundUser.Email == nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "user not found"})
    }

    if foundUser.Email != nil && !foundUser.Is_active {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "user hasnt been activated!"})
    } else {
        token, refreshToken, _ := helper.GenerateAllTokens(*foundUser.Email, *foundUser.Full_name, *foundUser.User_role, foundUser.User_id)
        helper.UpdateAllTokens(token, refreshToken, foundUser.User_id)
        err = userFindOneCollection.FindOne(ctx, bson.M{"user_id": foundUser.User_id}).Decode(&foundUser)

        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        c.JSON(http.StatusOK, foundUser)
    }
}

}

and heres my struct,

type User struct {
ID                 primitive.ObjectID     `json:"_id" bson:"_id"`
Email              *string                `json:"email" validate:"email,required"`
Password           *string                `json:"password" validate:"required,min=8"`
Is_active          bool                   `json:"is_active"` 

}

can anyone please give me some example, or give me any good reference for in this. Thanks!

eyatonics
  • 1
  • 1

0 Answers0