https://github.com/karpeleslab/contexter
https://github.com/karpeleslab/contexter
Last synced: 12 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/karpeleslab/contexter
- Owner: KarpelesLab
- License: mit
- Created: 2022-01-18T07:41:02.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2023-06-30T05:25:30.000Z (almost 3 years ago)
- Last Synced: 2024-06-20T05:23:35.060Z (almost 2 years ago)
- Language: Go
- Size: 11.7 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://godoc.org/github.com/KarpelesLab/contexter)
# Contexter
A dirty piece of code for fetching `context.Context` from the stack when it
cannot be passed normally.
## But why?
I turned out to need access to context.Context from a `MarshalJSON()` method
and found out there is no way to pass it easily. This is one of my attempts
at passing ctx across the stack.
So if your method that accepts a `context.Context` calls `json.Marshal()`, it
is likely the `MarshalJSON()` methods will be able to fetch the context using
`contexter.Context()`.
This said, we now have the [pjson](https://github.com/KarpelesLab/pjson) lib
that accepts contextes and is able to cleanly pass the context to the encoded
objects.
### My soul doesn't hurt enough
More stack based golang dark magic can be found online:
* https://github.com/jtolio/gls
## It doesn't work
There can be various reasons why this doesn't work, or stopped working.
* The method receiving a `context.Context` has been inlined and its parameters aren't available
* The variable containing the `context.Context` isn't used and was overwritten
* You're into a different goroutine (which means a new stack)
* Something changed in Go's runtime, stack display format, etc
* The architecture you're using does something that's not accounted for in this module
This is not an exact science, and using this package may result in the end of
the world, or your program crashing in ways go can't recover. You've been
warned.
# Usage
```go
ctx := contexter.Context()
```
This will automatically fetch the closest context.Context object found in the
stack that was passed as a context.Context object, or nil if none were found.
```go
var ctx context.Context
if contexter.Find(&ctx) {
// use ctx
}
```
This alternative version can find other kind of interfaces on the stack.