GO Gin如果我的代码的任何部分返回false,就会持续返回空状态。

huangapple go评论60阅读模式
英文:

GO Gin Keeps returning empty status if Any part of my code returns false

问题

我对Golang和Gin框架相对陌生。

我正在编写一些非常简单的API端点。但是我注意到Gin有一个非常奇怪的问题,如果我的代码中有任何返回false的条件或函数,那么剩下的代码或条件就不会被执行,Gin只会返回一个空状态的JSON:

{"status":""}

这里有一个非常简单的代码来解释我的意思:

在一个functions.go文件中,我有:

func VerifyUserLogin(username,password,userAgent string) (string, string) {
	userData := Users{}
	userQueryColumn := "username=?"
	// if they are trying to login with email
	if nEmailHelpers.EmailIsValid(username) == true{
		userQueryColumn = "email=?"
	}
	if getUserData := db.Select("password").Where(userQueryColumn, strings.ToLower(username)).First(&userData); getUserData.Error != nil {
		// Meaning there was an error, most likely no data found , so we just return false todo improve this error handling later to handle more specific errors

		return "", feedback["InvalidLogin"]
	} else {
		if getUserData.RowsAffected == 1 {
			if nSecurityHelpers.CheckPasswordHash(password, userData.Password)==true {
				token, tokenError := CreateToken(username, userAgent, false, 60)
				if tokenError == nil {
					return token, feedback["ValidLogin"]

				} else {
					return "", feedback["TokenNotGenerated"]

				}
			} else {
				return "", feedback["InvalidLogin"]
			}
		}
		return "", feedback["InvalidLogin"]

	}
}

在另一个引用functions.go文件的go文件中,我有:

func main(){
	router := gin.Default()
	router.POST ("login",loginUser)
	router.Run()
}

var feedback = userFeedback.Users()


// loginUser function to login a  user
func loginUser(c *gin.Context){
	requestBody := neielRequestsHelpers.RequestBody(c)
	username := requestBody["username"]
	password := requestBody["password"]
	userAgent := c.Request.Header.Get("User-Agent")
	token, loginMessage := userFunctions.VerifyUserLogin(username,password,userAgent)
	// todo come back and fix proper error message when user does not exist
	fmt.Println(loginMessage)
	if loginMessage==feedback["ValidLogin"]{
		c.JSON(http.StatusOK, gin.H{"status":loginMessage,"token":token})

	}else{
		c.JSON(http.StatusUnauthorized, gin.H{"status":feedback["InvalidLogin"]})

	}


}

如果所有的输入都正确,一切都很顺利(用户名存在且密码正确)。但是我必须处理用户名或密码无效的情况。如果由于任何原因getUserData或nSecurityHelpers.CheckPasswordHash()返回false,或者任何函数返回false,整个函数就会终止,不允许我按照我想要的方式处理错误并输出自定义的JSON响应。我只会得到这个{"status":""}。

我非常确定这个问题是由Gin引起的,但我不知道要激活或停用什么来允许我自己处理错误。我已经阅读了文档,但显然我漏掉了一些东西。

请帮助我,谢谢。

英文:

I am relatively new to Golang and Gin(framework)

I am writing some really simple API endpoints . But I notice something really weird about Gin, if there is any codition or function within my code that returns false the rest of my code or conditions does not get executed and Gin just returns a JSON with empty status :

{"status":""}

Here is a very simple code to explain what I mean

In a functions.go file I have :

func VerifyUserLogin(username,password,userAgent string) (string, string) {
	userData := Users{}
	userQueryColumn := "username=?"
	// if they are trying to login with email
	if nEmailHelpers.EmailIsValid(username) == true{
		userQueryColumn = "email=?"
	}
	if getUserData := db.Select("password").Where(userQueryColumn, strings.ToLower(username)).First(&userData); getUserData.Error != nil {
		//	Meaning there was an error, most likely no data found , so we just return false todo improve this error handling later to handle more specific errors

		return "", feedback["InvalidLogin"]
	} else {
		if getUserData.RowsAffected == 1 {
			if nSecurityHelpers.CheckPasswordHash(password, userData.Password)==true {
				token, tokenError := CreateToken(username, userAgent, false, 60)
				if tokenError == nil {
					return token, feedback["ValidLogin"]

				} else {
					return "", feedback["TokenNotGenerated"]

				}
			} else {
				return "", feedback["InvalidLogin"]
			}
		}
		return "", feedback["InvalidLogin"]

	}
}

In another go file that references the functions.go file I have :

func main(){
	router := gin.Default()
	router.POST ("login",loginUser)
	router.Run()
}

var feedback = userFeedback.Users()


// loginUser function to login a  user
func loginUser(c *gin.Context){
	requestBody := neielRequestsHelpers.RequestBody(c)
	username := requestBody["username"]
	password := requestBody["password"]
	userAgent := c.Request.Header.Get("User-Agent")
	token, loginMessage := userFunctions.VerifyUserLogin(username,password,userAgent)
	// todo come back and fix proper error message when user does not exist
	fmt.Println(loginMessage)
	if loginMessage==feedback["ValidLogin"]{
		c.JSON(http.StatusOK, gin.H{"status":loginMessage,"token":token})

	}else{
		c.JSON(http.StatusUnauthorized, gin.H{"status":feedback["InvalidLogin"]})

	}


}

If all my inputs are correct , all goes well (Username exists and password is correct). But I have to handle scenario where username or password is invalid .If for any reason getUserData or nSecurityHelpers.CheckPasswordHash() is false , or any function for that matter returns a boolean of false . The entire function just terminates and doesn't allow me handle the error the way I want and output custom JSON response. I just get this {"status":""}

I am 100% sure this issue is from Gin , but I don't know what to activate or deactivate to allow me handle errors on my own. I have read the docs, but its obvious I am missing something .

Kindly help me please .

答案1

得分: 0

我已经解决了这个问题,感谢所有试图帮助的人。
问题是在另一个文件中出现了一个拼写错误,"InValidLogin" 而不是 "InvalidLogin"。
这个错误非常微妙。

英文:

I have resolved this, thanks to everyone that tried to help
It was a typo error causing the issue "InValidLogin" instead of "InvalidLogin" in another file.
It was really subtle

huangapple
  • 本文由 发表于 2022年3月14日 10:37:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/71462463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定