在 go api 中获取错误消息和结果

getting error message along with result in go api

我在 API 中有一条路线,我可以通过 roles 获得用户。在这条路线中,如果我输入用户名,那么我将获得分配给 him/her 的所有 roles。但问题是它 returns 只有第一个结果。如果该角色存在于另一个对象中,则不会显示它。所以我评论了 return 行,一切正常,但随着结果,我收到错误消息:"user not found" 你们能告诉我我在做什么错误吗?
谢谢。
路线-

GET("/users/:username", controllers.GetUserByRole)

控制器-

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)
    }

    for _, a := range newUsers {
        for _, element := range a.Roles{
                if element == paramId {
            c.IndentedJSON(http.StatusOK, a)
            return     //if I comment this line line then I geting message `"user not found"` along with results
        }
    }
    }
    c.IndentedJSON(http.StatusNotFound, gin.H{"message": "user not found"})
}

URL: http://localhost:3000/users/Analyst
响应应该是:

  {
     "id": 1,
     "name": "Leanne Graham",
     "username": "Bret",
     "roles": ["Developer", "Analyst"],
  },
  {
    "id": 3,
    "name": "Clementine Bauch",
    "username": "Samantha",
    "roles": ["Manger", "Analyst"],
  }

但我是这样的(只有第一个匹配的):

  {
     "id": 1,
     "name": "Leanne Graham",
     "username": "Bret",
     "roles": ["Developer", "Analyst"],
  }

如果我评论 return 行,则响应为(期望结果 + 错误消息):

  {
     "id": 1,
     "name": "Leanne Graham",
     "username": "Bret",
     "roles": ["Developer", "Analyst"],
  },
  {
    "id": 3,
    "name": "Clementine Bauch",
    "username": "Samantha",
    "roles": ["Manger", "Analyst"],
  }{
    "message": "album not found"
}

完成 API 回复 -

[
  {
     "id": 1,
     "name": "Leanne Graham",
     "username": "Bret",
     "roles": ["Developer", "Analyst"],
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "roles": ["Assistant"],,
  },
  {
    "id": 3,
    "name": "Clementine Bauch",
    "username": "Samantha",
    "roles": ["Manger", "Analyst"],
  }
]

看起来你的 return 语句在你的 for 循环中,所以它找到第一个值并立即 returns。当您将其注释掉时,您的函数不会 return 因此它成功完成,然后打印错误消息。将 return 语句移到两个 for 循环之外,应该没问题。此外,添加通过错误标志发送错误消息的逻辑。还推荐使用 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
}

你可以这样做

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)