2 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
你可以這樣做
var userList []models.User
for _, a := range newUsers {
for _, element := range a.AssignedTo {
if element == paramId {
userList = append(userList, a)
}
}
}
if len(userList) == 0 {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "user not found"})
return
}
c.IndentedJSON(http.StatusOK, userList)

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
看起來(lái)你的 return 語(yǔ)句在你的 for 循環(huán)中,所以它找到第一個(gè)值并立即返回。當(dāng)您將其注釋掉時(shí),您的函數(shù)不會(huì)返回,因此它成功完成,然后打印錯(cuò)誤消息。將 return 語(yǔ)句移到兩個(gè) for 循環(huán)之外,應(yīng)該沒(méi)問(wèn)題。此外,通過(guò)錯(cuò)誤標(biāo)志添加用于發(fā)送錯(cuò)誤消息的邏輯。還建議使用 Manjeet Thakur 的替代解決方案。
func GetUserByRole(c *gin.Context) {
paramId := c.Param("username")
.............
.............
.............
var newUsers []models.User
iter := client.Collection("users").Documents(ctx)
for {
doc, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatalf("Failed to iterate: %v", err)
}
var tempUsers models.User
if err := doc.DataTo(&tempUsers); err != nil {
break
}
newUsers = append(newUsers, tempUsers)
}
var errorflag := 1
for _, a := range newUsers {
for _, element := range a.AssignedTo {
if element == paramId {
c.IndentedJSON(http.StatusOK, a)
errorflag := 0
//if I comment this line line then I geting message `"user not found"` along with results
}
}
}
if errorflag{
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "user not found"})
}
return
}
- 2 回答
- 0 關(guān)注
- 136 瀏覽
添加回答
舉報(bào)