I am trying to wrap my head around the GoLang type system, and there area a few things the confuse me.
So I have been working on the http library to try to understand this and I have come across the following that makes no sense.
package main
import (
"net/http"
"fmt"
"io/ioutil"
"io"
)
func convert(closer io.Closer) ([]byte) {
body, _ := ioutil.ReadAll(closer);
return body
}
func main() {
client := &http.Client{}
req, _ := http.NewRequest("GET", "https://www.google.com", nil)
response, _ := client.Do(req);
body, _ := ioutil.ReadAll(response.Body)
fmt.Println(body);
fmt.Println(convert(response.Body))
}
this is not about the fact that the convert function is not needed it is the fact that the response body is of type io.closer and the ioutil.Readall takes a io.reader, yet I can pass it in, in one instance but not if in another. Is there something that I am missing that is magically happening.
I know that the closer technically passes the reader interface as it implements the the Read method but that should be true in both the function and the main body.
Any insight would be great.
Thanks
it is the fact that the response body is of type io.closer
No, it is not. Declaration of Request.Body
is at http.Request
:
Body io.ReadCloser
The Request.Body
field is of type io.ReadCloser
, it is both an io.Reader
and an io.Closer
.
Since it is an io.Reader
(dynamic value of Request.Body
implements io.Reader
), you may use / pass it where an io.Reader
is required, e.g. to ioutil.ReadAll()
.
Since it also implements io.Closer
, you can also pass it where io.Closer
is required, like your convert()
function.
But inside convert the closer
param has static type io.Closer
, you can't use closer
where an in.Reader
is required. It might be (and in your case it is) that the dynamic type stored in closer
also implements io.Reader
, but there is no guarantee for this. Like in this example:
type mycloser int
func (mycloser) Close() error { return nil }
func main() {
var m io.Closer = mycloser(0)
convert(m)
}
In the above example closer
inside convert()
will hold a value of type mycloser
, which truly does not implement io.Reader
.
If your convert()
function intends to treat its parameter also as an io.Reader
, the parameter type should be io.ReadCloser
:
func convert(rc io.ReadCloser) ([]byte, error) {
body, err := ioutil.ReadAll(rc)
if err != nil {
return body, err
}
err = rc.Close()
return body, err
}