增加3.2小节

This commit is contained in:
astaxie
2012-09-04 18:10:34 +08:00
parent 726e9e375d
commit 5cf65385e2
3 changed files with 59 additions and 1 deletions

2
3.1.md
View File

@@ -56,7 +56,7 @@ HTTP是一种让Web服务器与浏览器(客户端)通过Internet发送与接收
## links
* [目录](<preface.md>)
* 上一: [Web基础](<3.md>)
* 上一: [Web基础](<3.md>)
* 下一节: [GO搭建一个web服务器](<3.2.md>)
## LastModified

58
3.2.md Normal file
View File

@@ -0,0 +1,58 @@
#3.2 GO搭建一个web服务器
前面小节已经介绍了Web是基于http协议的一个服务Go语言里面提供了一个完善的net/http包通过http包可以很方便的就搭建起来一个可以运行的web服务。使用这个包能很简单地对web的路由静态文件模版cookie等数据进行设置和操作。
##http包建立web服务器
package main
import (
"fmt"
"net/http"
"strings"
)
func sayhelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Println(r.Form) //这些信息是输出到服务器端的打印信息
fmt.Println("path", r.URL.Path)
fmt.Println("scheme", r.URL.Scheme)
fmt.Println(r.Form["url_long"])
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("val:", strings.Join(v, ""))
}
fmt.Fprintf(w, "Hello astaxie!") //这个写入到w的是输出到客户端的
}
func main() {
http.HandleFunc("/", sayhelloName)
http.ListenAndServe(":9090", nil)
}
上面这个代码我们build之后然后执行web.exe,这个时候其实已经在9090端口监听tcp链接请求了。
在浏览器输入`http://localhost:9090`
可以看到浏览器页面输出了`Hello astaxie!`
可以换一个地址试试:`http://localhost:9090/?url_long=111&url_long=222`
看看浏览器输出的是什么,服务器输出的是什么?
在服务器端输出的信息如下:
![](images/3.2.goweb.png?raw=true)
我们看到上面的代码要编写一个web服务器很简单只要调用http包的两个函数就可以了。
## links
* [目录](<preface.md>)
* 上一节: [Web工作方式](<3.1.md>)
* 下一节: [Go如何使得web工作](<3.3.md>)
## LastModified
* $Id$

BIN
images/3.2.goweb.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB