Update 15.2.md

This commit is contained in:
glight2000
2015-12-10 12:26:56 +08:00
parent b28ed460de
commit 7485bf8ddc

View File

@@ -66,7 +66,45 @@ http.ListenAndServe(":8080", http.HandlerFunc(HelloServer))
fmt.Fprintf(w, "<h1>%s<h1><div>%s</div>", title, body)
```
来构建一个非常简单的网页并插入`title`和`body`的值
如果你需要更多复杂的替换,使用模板包(请看[章节15.7](15.7.md)
3如果你需要使用安全的https连接使用`http.ListenAndServeTLS()`代替`http.ListenAndServe()`
4`http.HandleFunc("/", Hfunc)`中的`HFunc`是一个处理函数,如下:
```go
func HFunc(w http.ResponseWriter, req *http.Request) {
...
}
```
也可以使用这种方式:`http.Handle("/", http.HandlerFunc(HFunc))`
上边的`HandlerFunc`只是一个类型名称,它定义如下:
```go
type HandlerFunc func(ResponseWriter, *Request)
```
它是一个可以把普通的函数当做HTPP处理器的适配器。如果`f`函数声明的合适,`HandlerFunc(f)`就是一个执行了`f`函数的处理器对象。
`http.Handle`的第二个参数也可以是`T`的一个obj对象`http.Handle("/", obj)`给T提供了`SereHTTP`方法实现了http的`Handler`接口:
```go
func (obj *Typ) ServeHTTP(w http.ResponseWriter, req *http.Request) {
...
}
```
这个用法在[章节15.8](15.8.md)类型`Counter`和`Chan`上使用过。只要实现了`http.Handler``http`包就可以处理任何HTTP请求。
练习 15.2[webhello2.go](exercises/chapter_15/webhello2.go)
>编写一个网页服务器监听端口9999有如下处理函数
>i)当请求`http://localhost:9999/hello/Name`时,响应:`hello Name`(Name需是一个合法的姓比如Chris或者Madeleine)
>ii)当请求`http://localhost:9999/shouthello/Name`时,响应:`hello NAME`
练习 15.3[hello_server.go](exercises/chapter_15/hello_server.go)
>