From b28ed460debbc1e40b5a3a6e306c39f750dc5e4a Mon Sep 17 00:00:00 2001 From: glight2000 <173959153@qq.com> Date: Wed, 9 Dec 2015 23:38:41 +0800 Subject: [PATCH] Update 15.2.md --- eBook/15.2.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/eBook/15.2.md b/eBook/15.2.md index 15057f8..600d3b1 100644 --- a/eBook/15.2.md +++ b/eBook/15.2.md @@ -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, "