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

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

URL 没问题,因为 wget 可以正常使用,但是当我运行时,这个 buf 只是一个空字符串,而 nr 总是零。我需要做什么才能从 response 中获取数据?编译器拒绝了 .ReadAll 和我尝试过的其他东西。

输出看起来像这样:

Status is 200 OK
Got 0 bytes
Got ''

最佳答案

尝试给 slice buf 一个大小,例如

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

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.

关于go - 如何在 Go 中使用 .Read 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1721212/

相关文章:

go - 为什么 bcrypt 库 CompareHashAndPassword 方法很慢?

json - 从毫秒转换为 Golang 中的时间

oop - Go语言中的静态类方法

google-app-engine - 在 golang 的谷歌应用引擎上获取 asna 重定向 url 参数

methods - 具有相同名称和数量但类型不同的 Golang 方法

go - 意外的 slice 追加行为

go - 我如何在 Google Cloud Functions 上使用带有 Go 的子包?

Golang 将类型 [N]byte 转换为 []byte

go - 像 erlang spawn 这样的 goroutine 可以跨多个主机透明地处理吗?

具有自定义签名的 Golang 错误组超过函数