Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Enhancement]: Option to get *gin.Context from context.Context #2824

Closed
ifaisalalam opened this issue Aug 14, 2021 · 1 comment · Fixed by #2825
Closed

[Enhancement]: Option to get *gin.Context from context.Context #2824

ifaisalalam opened this issue Aug 14, 2021 · 1 comment · Fixed by #2825

Comments

@ifaisalalam
Copy link
Contributor

ifaisalalam commented Aug 14, 2021

Description

GIN's gin.Context implements Go context.Context interface, so we can do something like

ctx, cancel := context.WithCancel(ginCtx)

and pass this ctx around.

Can we make changes in the GIN's context Value(key interface{}) interface{} method to return the original GIN's context?

Expectations

package demo

import (
    "context"

    "github.com/gin-gonic/gin"
)

func AwesomeFun(ginCtx *gin.Context) {
    ctx, cancel := context.WithCancel(ginCtx)
    defer cancel()

    test(ctx)
}

func test(ctx context.Context) {
    ginCtx, ok := ctx.Value(gin.ContextKey).(*gin.Context)
    if !ok {
        return
    }

    // We now have the GIN context in ginCtx var
}
@ifaisalalam ifaisalalam changed the title Option to get gin.Context from context.Context [Enhancement]: Option to get *gin.Context from context.Context using .Value() Aug 14, 2021
@ifaisalalam ifaisalalam changed the title [Enhancement]: Option to get *gin.Context from context.Context using .Value() [Enhancement]: Option to get *gin.Context from context.Context Aug 14, 2021
@samc1213
Copy link

samc1213 commented Jan 3, 2024

For anyone trying to test a gin handler by manually cancelling a context, this code snippet might help:

req := httptest.NewRequest("POST", "/my_api", bytes.NewReader(body))
resp := httptest.NewRecorder()
tc, engine := gin.CreateTestContext(resp)
engine.ContextWithFallback = true
newReqCtx, cancel := context.WithCancel(req.Context())
req = req.WithContext(newReqCtx)
tc.Request = req

handlers.HandleMyApi(tc) // This implements /my_api

cancel() // Call this when you want to simulate client disconnect - `tc` will be context canceled

This is helpful to simulate a client disconnecting in the middle of a request in a unit/functional test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants