package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
)
func main() {
for _, url := range os.Args[1:] {
//练习 1.8
if !strings.HasPrefix(url, "http://") {
url = "http://" + url
}
resp, err := http.Get(url)
if err != nil {
fmt.Fprintf(os.Stderr, "fetch : %v\n", err)
os.Exit(1)
}
//练习 1.9
fmt.Println(resp.Status)
/*
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)
os.Exit(1)
}
fmt.Println(body)
*/
//练习 1.7
_, err = io.Copy(os.Stdout, resp.Body)
resp.Body.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)
os.Exit(1)
}
}
}
Go语言圣经 - 习题 - 1.5. 获取URL
最新推荐文章于 2024-06-15 12:11:07 发布