packagemainimport ("fmt""net/http")var urls = []string{"http://www.google.com/","http://golang.org/","http://blog.golang.org/",}funcmain() {// Execute an HTTP HEAD request for all url's// and returns the HTTP status string or an error string.for _, url :=range urls { resp, err := http.Head(url)if err !=nil { fmt.Println("Error:", url, err) } fmt.Println(url, ": ", resp.Status) }}
输出为:
http://www.google.com/ : 302 Found
http://golang.org/ : 200 OK
http://blog.golang.org/ : 200 OK
译者注 由于国内的网络环境现状,很有可能见到如下超时错误提示:
Error: http://www.google.com/ Head http://www.google.com/: dial tcp 216.58.221.100:80: connectex: A connection attempt failed because the connected pa
rty did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
packagemainimport ("encoding/xml""fmt""net/http")/*这个结构会保存解析后的返回数据。他们会形成有层级的XML,可以忽略一些无用的数据*/typeStatusstruct { Text string}typeUserstruct { XMLName xml.Name Status Status}funcmain() {// 发起请求查询推特Goodland用户的状态 response, _ := http.Get("http://twitter.com/users/Googland.xml")// 初始化XML返回值的结构 user :=User{xml.Name{"", "user"}, Status{""}}// 将XML解析为我们的结构 xml.Unmarshal(response.Body, &user) fmt.Printf("status: %s", user.Status.Text)}
输出:
status: Robot cars invade California, on orders from Google: Google has been testing self-driving cars ... http://bit.ly/cbtpUN http://retwt.me/97p<exit code="0" msg="process exited normally"/>