goroutine求助

leavesdrift · 2017-11-23 13:53:02 · 992 次点击

@channel

package main

import (
    "net/http"
    "io/ioutil"
    "fmt"
    "time"
)

func fetch(ch chan string){
    resp, err := http.Get("http://www.baidu.com")
    defer resp.Body.Close()

    if err != nil {
        panic(err)
    }

    body, err := ioutil.ReadAll(resp.Body)
    ch <-string(body)
}

func main(){
    ch := make(chan string)
    go fetch(ch)

    select {
        case rs := <-ch:
            fmt.Printf("success\n\t->%s", rs)
        case <-time.After(3*time.Second):
            fmt.Printf("failed\n\t->nil")
    } 
}

改成这样了,因为 case 中读取了一次 ch,之后Printf里面又读取了一次

#3
更多评论

原来是 channel 不能二次读取,自己发现了。

#1

啥输出都没有?感觉不应该呀!

PS: defer 要放在 err 判断之后。

#2