5

尝试使用 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我尝试过的其他事情。

输出如下所示:

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

3 回答 3

7

尝试给切片 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.
于 2009-11-12T10:40:37.237 回答
0

尝试改编教程中的 cat 示例:

fmt.Printf ("Status is %s\n", response.Status);
var nr int;

const NBUF = 512;
var buf [NBUF]byte;

for {
    switch nr, _ := response.Body.Read(&buf); true {
    case nr < 0:
        os.Exit(1);
    case nr == 0:  // EOF
        return;
    case nr > 0:
        if nw, _ := os.Stdout.Write(buf[0:nr]); nw != nr {
            fmt.Printf("error\n");
        }
    }
}

输出:

$ ./8.out 
Status is 200 OK
{"id":181548,"gravatarHtml":"\u003cimg src=\"http://www.gravatar.com/avatar/f4a286fa31d1359ee92113823a70a738?s=50&amp;d=identicon&amp;r=PG\" height=\"50\" width=\"50\" alt=\"\"\u003e","profileUrl":"http://stackoverflow.com/users/181548/kinopiko","displayName":"Kinopiko","reputation":"4,674","badgeHtml":"\u003cspan title=\"1 gold badge\"\u003e\u003cspan class=\"badge1\"\u003e&#9679;\u003c/span\u003e\u003cspan class=\"badgecount\"\u003e1\u003c/span\u003e\u003c/span\u003e\u003cspan title=\"5 silver badges\"\u003e\u003cspan class=\"badge2\"\u003e&#9679;\u003c/span\u003e\u003cspan class=\"badgecount\"\u003e5\u003c/span\u003e\u003c/span\u003e\u003cspan title=\"21 bronze badges\"\u003e\u003cspan class=\"badge3\"\u003e&#9679;\u003c/span\u003e\u003cspan class=\"badgecount\"\u003e21\u003c/span\u003e\u003c/span\u003e"}
于 2009-11-12T11:26:32.123 回答
0

此处未定义 buf 的大小,因此使用 0 大小创建 buf。创建具有一定大小的 buf 应该会有所帮助。buf = make([]byte, 500)

$ cat slice.go 
package main

import (
    "fmt"
    "net/http"
    "os"
)

func main() {
    kinopiko_flair := "http://stackoverflow.com"
    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
    fmt.Printf("Initially :capacity of slice is %d and length is %d \n ", cap(buf), len(buf))
    buf = make([]byte, 500) // THIS SHOULD HELP
    fmt.Printf("UPDATE: capacity of slice is %d and length is %d \n ", cap(buf), len(buf))
    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)
}

输出

$ go run slice.go 
    Status is 200 OK
     Initially :capacity of slice is 0 and length is 0 
     UPDATE: capacity of slice is 500 and length is 500 
     Got 500 bytes
    Got '<!DOCTYPE html>


        <html class="html__responsive html__unpinned-leftnav">

        <head>

            <title>Stack Overflow - Where Developers Learn, Share, &amp; Build Careers</title>
            <link rel="shortcut icon" href="https://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico?v=4f32ecc8f43d">
            <link rel="apple-touch-icon image_src" href="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png?v=c78bd457575a">
            <link rel="search" type="application/opensear'
于 2019-09-21T14:33:06.723 回答