Programmatically set an url parameter in gin context for testing purpose

Issue

I am writing some test suites for gin middlewares. I found a solution to test them without having to run a full router engine, by creating a gin context like this :

w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)

The goal is to test my function by calling :

MyMiddleware(c)

// Then I use c.MustGet() to check if every expected parameter has been transmitted to gin
// context, with correct values.

One of my middlewares relies on c.Param(). Is it possible to programatically set an Url param in gin (something like c.SetParam(key, value)) before calling the middleware ? This is only for test purpose so I don’t mind non-optimized solutions.

Solution

Finally figured it out by using IntelliJ to inspect the structure, I can just set it the raw way :

c.Params = []gin.Param{
    {
        Key: "id",
        Value: "first document",
    },
}

Answered By – KawaLo

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.