Search code examples
gogetpostmanmgogo-gin

Unable to get Object Id from Get Url in Postman


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.

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


Solution

  • 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",
        })
    }