package main
import (
"fmt"
"net/http"
)
var urls = []string{
"http://www.google.com/",
"http://golang.org/",
"http://blog.golang.org/",
}
func main() {
// 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.
2011/09/30 11:24:15 Get: Get http://www.google.bex: dial tcp www.google.bex:80:GetHostByName: No such host is known.
译者注 和上一个例子相似,你可以把google.com更换为一个国内可以顺畅访问的网址进行测试
在下边的程序中,我们获取一个twitter用户的状态,通过xml包将这个状态解析成为一个结构:
package main
import (
"encoding/xml"
"fmt"
"net/http"
)
/*这个结构会保存解析后的返回数据。
他们会形成有层级的XML,可以忽略一些无用的数据*/
type Status struct {
Text string
}
type User struct {
XMLName xml.Name
Status Status
}
func main() {
// 发起请求查询推特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"/>