Skip to content

Instantly share code, notes, and snippets.

@ancientlore
Created June 25, 2015 23:52
Show Gist options
  • Save ancientlore/edc3c8d5fda590253e49 to your computer and use it in GitHub Desktop.
Save ancientlore/edc3c8d5fda590253e49 to your computer and use it in GitHub Desktop.
ContextReadCloser issue
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
)
var next = 0
type ContextReadCloser interface {
io.ReadCloser
Context() map[interface{}]interface{}
}
type FooReadCloser interface {
io.ReadCloser
Foo() int
}
type X struct {
Body io.ReadCloser
}
type contextReadCloser struct {
io.ReadCloser
context map[interface{}]interface{}
}
func (crc *contextReadCloser) Context() map[interface{}]interface{} {
return crc.context
}
type fooReadCloser struct {
io.ReadCloser
foo int
}
func (frc *fooReadCloser) Foo() int {
return frc.foo
}
func getContextReadCloser(req *X) ContextReadCloser {
crc, ok := req.Body.(ContextReadCloser)
if !ok {
crc = &contextReadCloser{
ReadCloser: req.Body,
context: make(map[interface{}]interface{}),
}
req.Body = crc
}
return crc
}
func getFooReadCloser(req *X) FooReadCloser {
frc, ok := req.Body.(FooReadCloser)
if !ok {
next = next + 1
frc = &fooReadCloser{
ReadCloser: req.Body,
foo: next,
}
req.Body = frc
}
return frc
}
func main() {
var req X
var b bytes.Buffer
req.Body = ioutil.NopCloser(&b)
crc := getContextReadCloser(&req)
crc.Context()["foo"] = "bar"
crc = getContextReadCloser(&req)
fmt.Printf("%#v\n", crc.Context()["foo"])
frc := getFooReadCloser(&req)
fmt.Printf("%#v\n", frc.Foo())
crc = getContextReadCloser(&req)
fmt.Printf("%#v\n", crc.Context()["foo"])
frc = getFooReadCloser(&req)
fmt.Printf("%#v\n", frc.Foo())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment