尝试使用 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/