小编典典

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

go

尝试使用Go的http包时,我无法确定的语法.Read。尽管我尝试了其他一些被编译器拒绝的其他事情,但这里只有我标记的以下内容是我必须编译的。

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);
}

该URL可以,因为wget可以正常使用,但是在我运行时,它buf只是一个空字符串,nr并且始终为零。我需要怎么做才能取出数据response?编译器拒绝了.ReadAll其他尝试。

输出看起来像这样:

状态为200 OK
得到了0个字节
得到 ''

阅读 513

收藏
2020-07-02

共1个答案

小编典典

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

 buf := make([]byte,128);

读取器最多读取给定缓冲区的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.
2020-07-02