diff --git a/eBook/15.3.md b/eBook/15.3.md index e4d2d67..f8b9adb 100644 --- a/eBook/15.3.md +++ b/eBook/15.3.md @@ -46,4 +46,80 @@ rty did not properly respond after a period of time, or established connection f 示例 15.8 [http_fetch.go](examples/chapter_15/http_fetch.go): ```go +package main + +import ( + "fmt" + "io/ioutil" + "log" + "net/http" +) + +func main() { + res, err := http.Get("http://www.google.com") + checkError(err) + data, err := ioutil.ReadAll(res.Body) + checkError(err) + fmt.Printf("Got: %q", string(data)) +} + +func checkError(err error) { + if err != nil { + log.Fatalf("Get : %v", err) + } +} ``` + +当访问不存在的网站时,这里有一个`CheckError`输出错误的例子: +``` +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`包将这个状态解析成为一个结构: + +示例 15.9 [twitter_status.go](examples/chapter_15/twitter_status.go) +```go +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 +``` +**译者注** 和上边的示例相似,你可能无法获取到xml数据,另外由于go版本的更新,`xml.Unmarshal`函数的第一个参数需是[]byte类型,而无法传入`Body`。 + +我们会在[章节15.4](15.4.md)中用到`http`包中的其他重要的函数: +* `http.Redirect(w ResponseWriter, r *Request, url string, code int)`:这个函数会让浏览器重定向到url(是请求的url的相对路径)以及状态码。 +* `http.NotFound(w ResponseWriter, r *Request)`:这个函数将返回网页没有找到,HTTP 404错误。 +* `http.Error(w ResponseWriter, error string, code int)`:这个函数返回特定的错误信息和HTTP代码。 +* 另`http.Request`对象的一个重要属性`req`:`req.Method`,这是一个包含`GET`或`POST`字符串,用来描述网页是以何种方式被请求的。 + +``` +