Created
June 25, 2015 23:52
-
-
Save ancientlore/edc3c8d5fda590253e49 to your computer and use it in GitHub Desktop.
ContextReadCloser issue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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