github.com/KarpelesLab/contexter@v1.0.2/README.md (about) 1 [](https://godoc.org/github.com/KarpelesLab/contexter) 2 3 # Contexter 4 5 A dirty piece of code for fetching `context.Context` from the stack when it 6 cannot be passed normally. 7 8 ## But why? 9 10 I turned out to need access to context.Context from a `MarshalJSON()` method 11 and found out there is no way to pass it easily. This is one of my attempts 12 at passing ctx across the stack. 13 14 So if your method that accepts a `context.Context` calls `json.Marshal()`, it 15 is likely the `MarshalJSON()` methods will be able to fetch the context using 16 `contexter.Context()`. 17 18 ### My soul doesn't hurt enough 19 20 More stack based golang dark magic can be found online: 21 22 * https://github.com/jtolio/gls 23 24 ## It doesn't work 25 26 There can be various reasons why this doesn't work, or stopped working. 27 28 * The method receiving a `context.Context` has been inlined and its parameters aren't available 29 * The variable containing the `context.Context` isn't used and was overwritten 30 * You're into a different goroutine (which means a new stack) 31 * Something changed in Go's runtime, stack display format, etc 32 * The architecture you're using does something that's not accounted for in this module 33 34 This is not an exact science, and using this package may result in the end of 35 the world, or your program crashing in ways go can't recover. You've been 36 warned. 37 38 # Usage 39 40 ```go 41 ctx := contexter.Context() 42 ``` 43 44 This will automatically fetch the closest context.Context object found in the 45 stack that was passed as a context.Context object, or nil if none were found. 46 47 ```go 48 var ctx context.Context 49 if contexter.Find(&ctx) { 50 // use ctx 51 } 52 ``` 53 54 This alternative version can find other kind of interfaces on the stack.