新手希望练习 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")
}
}
```
```
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")
}
}
```
#8
更多评论