douhuigan8063 2018-08-23 04:50
浏览 64
已采纳

无法从邮递员中的“获取网址”获取对象ID

It Seems like my url is mismatching as its showing a 404 error, I tried changing the url at both postman and my code too.Also tried to work out with object id conversion to see if the 404 is being caused by that.Below is my code.

func main() {
    r := gin.Default()
    r.GET("/get-custone/:_id", getDetailone)
    r.Run()
} 
func getDetailone(c *gin.Context) {
    session := connect()
    defer session.Close()
    col := session.DB("test").C("cust")
    var results Person
    idstring:=c.Param("_id")
    oid:=bson.ObjectId(idstring)
    err := col.Find(bson.M{"_id":oid}).One(&results)
    if err != nil {
        panic(err)
    }
    c.JSON(200, gin.H{
        "message": "success",
    })
}

here's the screenshot from Postman

enter image description here

  • 写回答

1条回答 默认 最新

  • dsv38843 2018-08-23 11:50
    关注

    In Postman you are trying to pass _id as a query string whereas you are waiting for a path parameter in your code.

    What you want to do is that:

    curl -X GET http://localhost:8080/get-custone/5b7d...
    

    If you prefer using query string parameter, you should rather do something like that (I did not test the code):

    func main() {
        r := gin.Default()
        r.GET("/get-custone", getDetailone)
        r.Run()
    } 
    func getDetailone(c *gin.Context) {
        session := connect()
        defer session.Close()
        col := session.DB("test").C("cust")
        var results Person
        idstring:= c.Query("_id")
        oid:=bson.ObjectId(idstring)
        err := col.Find(bson.M{"_id":oid}).One(&results)
        if err != nil {
            panic(err)
        }
        c.JSON(200, gin.H{
            "message": "success",
        })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?