新手希望练习 goroutine 爬取资源并且实现超时控制,但下列程序无输出。
```
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 <-ch:
fmt.Printf("success\n\t->%s", <-ch)
case <-time.After(3*time.Second):
fmt.Printf("failed\n\t->nil")
}
}
```
<a href="/user/channel" title="@channel">@channel</a>
```go
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
更多评论