I've started studying Go recently as a side project and have been trying to get a better handle around the Reader interface. Specifically, I'm trying to get contents from a website, and then reading it to a bytes slice.
I am aware that the ioutils.ReadAll function is the canonical way to get the data, but I'm curious why the original function I wrote has repeated content at the end of the output.
Code: package main
import(
"net/http"
"fmt"
)
func main() {
// retrieve url from hacker news.
resp, err := http.Get("http://ift.tt/eY2lHV")
if err != nil {
// handle error
}
defer resp.Body.Close()
text := make([]byte, 500)
buf := make([]byte, 200)
i, _ := resp.Body.Read(buf)
for i != 0 {
text = append(text,buf...)
i, _ = resp.Body.Read(buf)
}
fmt.Println(resp.ContentLength)
fmt.Println(resp.Status)
fmt.Printf("%q\n", text)
}
Content:
(...)Search:\n <input type=\"text\" name=\"q\" value=\"\" size=\"17\" autocorrect=\"off\" spellcheck=\"false\" autocapitalize=\"off\" autocomplete=\"false\"></form>\n </center></td></tr>
</table></center></body></html>\nput type=\"text\" name=\"q\" value=\"\" "
As you can see, for a reason I don't quite understand, one part of the text is repeated at the end after the closed tags; 'nput type=\"text\" name=\"q\" value=\"\" "'.
Maybe this is something related to the buffer not being cleared maybe? Could anyone offer some insight as to what I am getting wrong?
Aucun commentaire:
Enregistrer un commentaire