如何在Go中使用.Read函数?

5 go

试图使用Go的http包,我无法弄清楚语法.Read.以下标记为HERE是我唯一需要编译的东西,尽管我尝试了其他一些被编译器拒绝的东西.

package main
import "fmt";
import "http";
import "os";

func main () {
    kinopiko_flair := "http://stackoverflow.com/users/flair/181548.json";
    response, _, error := http.Get (kinopiko_flair);
    if (error != nil) {
        // I want to print out the error too.
        fmt.Printf ("Error getting %s\n", kinopiko_flair);
        os.Exit (1);
    }
    fmt.Printf ("Status is %s\n", response.Status);
    var nr int;
    var buf []byte;
    nr, error = response.Body.Read (buf); // HERE
    if (error != nil) {
        // I want to print out the error too.
        fmt.Printf ("Error reading response.\n");
        os.Exit (1);
    }
    response.Body.Close ();
    fmt.Printf ("Got %d bytes\n", nr);
    fmt.Printf ("Got '%s'\n", buf);
}
Run Code Online (Sandbox Code Playgroud)

URL是正常的,因为wget它很好,但是当我运行时,这buf只是一个空字符串,nr始终为零.我需要做些什么来获取数据response?编译器拒绝了.ReadAll我尝试过的其他事情.

输出如下所示:

Status is 200 OK
Got 0 bytes
Got ''

Sco*_*les 7

尝试给切片buf一个大小,例如

 buf := make([]byte,128);
Run Code Online (Sandbox Code Playgroud)

Reader读取它给出的缓冲区的len().

来自io.go

// Reader is the interface that wraps the basic Read method.
//
// Read reads up to len(p) bytes into p.  It returns the number of bytes
// read (0 <= n <= len(p)) and any error encountered.
// Even if Read returns n < len(p),
// it may use all of p as scratch space during the call.
// If some data is available but not len(p) bytes, Read conventionally
// returns what is available rather than block waiting for more.
//
// At the end of the input stream, Read returns 0, os.EOF.
// Read may return a non-zero number of bytes with a non-nil err.
// In particular, a Read that exhausts the input may return n > 0, os.EOF.
Run Code Online (Sandbox Code Playgroud)