Update 15.2.md

This commit is contained in:
glight2000
2015-12-09 23:38:41 +08:00
parent 57df7df397
commit b28ed460de

View File

@@ -25,7 +25,48 @@ Http是一个比tcp更高级的协议它描述了客户端浏览器如何与
示例 15.6 [hello_world_webserver.go](examples/chapter_15/hello_world_webserver.go)
```go
package main
import (
"fmt"
"log"
"net/http"
)
func HelloServer(w http.ResponseWriter, req *http.Request) {
fmt.Println("Inside HelloServer handler")
fmt.Fprintf(w, "Hello,"+req.URL.Path[1:])
}
func main() {
http.HandleFunc("/", HelloServer)
err := http.ListenAndServe("localhost:8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}
```
使用命令行启动程序,会打开一个命令窗口显示如下文字:
```
Starting Process E:/Go/GoBoek/code_examples/chapter_14/hello_world_webserver.exe
...
```
然后打开你的浏览器并输入url地址`http://localhost:8080/world`,浏览器就会出现文字:`Hello, world`,网页服务器会响应你在`:8080/`后边输入的内容
使用`fmt.Println`在控制台打印状态在每个handler被请求的时候在他们内部打印日志会很有帮助
注:
1前两行没有错误处理代码可以替换成以下写法
```go
http.ListenAndServe(":8080", http.HandlerFunc(HelloServer))
```
2`fmt.Fprint`和`fmt.Fprintf`都是用来写入`http.ResponseWriter`的不错的函数(他们实现了`io.Writer`)。
比如我们可以使用
```go
fmt.Fprintf(w, "<h1>%s<h1><div>%s</div>", title, body)
```
来构建一个非常简单的网页并插入`title`和`body`的值
如果你需要更多复杂的替换,使用模板包(请看[章节15.7](15.7.md)