4 ms·
Not sure what buffer overruns you are referring to, or why this case requires reflection at all. err := readMessage(reader) if n, ok := err.(net.Error); ok
by agentS 14y ago
Not sure what buffer overruns you are referring to, or why this case requires reflection at all.
err := readMessage(reader)
if n, ok := err.(net.Error); ok && n.Timeout() {
// handle timeout
} else if err != nil {
// handle other errors
}
You can see an example of exactly this pattern here: http://golang.org/src/pkg/net/http/server.go?s=29962:30008#L1000 http://golang.org/src/pkg/net/http/server.go?s=29962:30008#L...
- eternalban 14y agoYou did not carefully read the GP. IO read/write functions are not limited to the net package. net.Conn supports a subset of these (interface types) and it is entirely idiomatic and possible for a net.Conn flavor to endup at some deep layer of your code in a function accepting generic io in args. Functions taking non-net "in args" returning "error" can not be assumed to always return "net.Error". You will need to test the type (reflectively) and then safely cast. For example : http://golang.org/pkg/io/#ReadFull http://golang.org/pkg/io/#ReadFull Is it "non-idiomatic" to wrap net.Conn as another non-net package type and then use it? http://golang.org/src/pkg/net/net.go#L22 http://golang.org/src/pkg/net/net.go#L22
- agentS 14y agoTo be clear, the two-valued cast I used in my example never panics. It returns (casted value, true) or (nil, false). No need to write any reflective functions. As to your example of io.ReadFull: what about it? If it gets an EOF before filling the buffer you passed in, it'll return ErrUnexpectedEOF per the documentation. If it gets any other error, it'll return it instead. I haven't actually looked at the source in a while but that's how almost all of the byte stream functions work.