Is there a way to transform
gin.Context
to context.Context
in Go?
What should be used in building a Go microservice?
Asked
Active
Viewed 1.1k times
1 Answers
28
The standard library's context.Context
type is an interface, with the following methods:
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key interface{}) interface{}
So any type that has these methods is a context.Context
.
Looking at the gin documentation, we see that the gin.Context
type has all of these methods:
So it's already a context.Context
. No conversion or transformation necessary.

Jonathan Hall
- 75,165
- 16
- 143
- 189
-
How do you convert `*gin.Context` to `*context.Context`? – wizulus Aug 26 '20 at 18:11
-
1@wizulus: You don't. `*context.Context` doesn't make sense. `*gin.Context` already is a `context.Context`, so don't do any conversion. – Jonathan Hall Aug 26 '20 at 19:09
-
If we weren't talking about pointers, I would agree. But my compiler seems to complain about this. A `pointer to gin.Context` is not a `pointer to context.Context`, even though `gin.Context` implements the `context.Context` interface. In my code, I had to de-reference the first pointer into a new variable, then use a pointer to that variable. I wonder if there's a way to do that without an intermediate variable, and preserve the memory location. – wizulus Aug 27 '20 at 16:51
-
2Yes, don't use a pointer to `context.Context`. pointers to interfaces practically never make any sense. If you're using `*context.Context` in your code, that is the bug. – Jonathan Hall Aug 27 '20 at 16:53
-
4But the context methods in gin.Context are no-ops. I think in most practical cases you actually want `ginCtx.Request.Context()` – aquavitae Feb 14 '22 at 08:08