mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-11-13 17:36:12 +08:00
Update 15.2.md
This commit is contained in:
@@ -25,7 +25,48 @@ Http是一个比tcp更高级的协议,它描述了客户端浏览器如何与
|
|||||||
|
|
||||||
示例 15.6 [hello_world_webserver.go](examples/chapter_15/hello_world_webserver.go):
|
示例 15.6 [hello_world_webserver.go](examples/chapter_15/hello_world_webserver.go):
|
||||||
```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))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user