这是我在 Postman 中的 URL:http://localhost:8000/filter?Name=Srinu
我正在传递一个查询字符串以根据查询获取数据库上的记录。
在我的具有姓名、性别和年龄的数据库中,我应该如何根据下面的代码片段编写 switch 语句,我必须根据我的查询获取数据?
switch ? {
case "Name":
fiName := bson.D{{"Name", name}}
err = uc.session.DB(DB_NAME).C(DB_COLLECTION).Find(fiName).All(&json1)
if err == nil {
c.Writer.Header().Set("Content-Type", "application/json")
c.JSON(201, &json1)
} else {
c.JSON(500, gin.H{"result": "An error occured"})
}
case "Gender":
fiGender := bson.D{{"Gender", gender}}
err = uc.session.DB(DB_NAME).C(DB_COLLECTION).Find(fiGender).All(&json1)
if err == nil {
c.Writer.Header().Set("Content-Type", "application/json")
c.JSON(201, &json1)
} else {
c.JSON(500, gin.H{"result": "An error occured"})
}
case "Age":
fiAge := bson.D{{"Age", age}}
err = uc.session.DB(DB_NAME).C(DB_COLLECTION).Find(fiAge).All(&json1)
if err == nil {
c.Writer.Header().Set("Content-Type", "application/json")
c.JSON(201, &json1)
} else {
c.JSON(500, gin.H{"result": "An error occured"})
}
}
最佳答案
使用以下代码:
r := ctx.Request
r.ParseForm()
switch {
case len(r.Form["Name"]) > 0:
name := r.Form["Name"][0]
fiName := bson.D{{"Name", name}}
err = uc.session.DB(DB_NAME).C(DB_COLLECTION).Find(fiName).All(&json1)
...
}
来电
r.ParseForm()
套r.Form
使用从请求中解析的数据。字段
r.Form
是字符串 slice 的映射。如果查询中存在参数,则该参数的字符串 slice 的长度大于零。声明
name := r.Form["Name"][0]
获取 Name
的第一个参数值.如果请求是 http://localhost:8000/filter?Name=Srinu&Name=Reflect
,然后是第二个值 Reflect
被默默地忽略。
关于go - 我应该如何根据 URL 切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60705375/