Go 我应该如何根据URL进行切换
这是我在邮递员中的URL:Go 我应该如何根据URL进行切换,go,go-gin,Go,Go Gin,这是我在邮递员中的URL:http://localhost:8000/filter?Name=Srinu 我正在传递一个查询字符串,以便根据查询获取数据库上的记录 在我有姓名、性别和年龄的数据库中,我应该如何根据下面的代码片段编写switch语句,即我必须根据我的查询获取数据 switch ? { case "Name": fiName := bson.D{{"Name", name}} err = uc.sessi
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
是字符串片段的映射。如果查询中存在参数,则该参数的字符串片段长度大于零
语句name:=r.Form[“name”][0]
获取name
的第一个参数值。如果请求是http://localhost:8000/filter?Name=Srinu&Name=Reflect
,则第二个值Reflect
将被静默忽略
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)
...
}