原文连接golang
Go(Golang.org)是在标准库中提供HTTP协议支持的系统语言,经过他能够快速简单的开发一个web服务器。同时,Go语言为开发者提供了不少便利。这本篇博客中咱们将列出使用Go开发HTTP 服务器的方式,而后分析下这些不一样的方法是如何工做,为何工做的。web
在开始以前,假设你已经知道Go的一些基本语法,明白HTTP的原理,知道什么是web服务器。而后咱们就能够开始HTTP 服务器版本的著名的“Hello world”。浏览器
首先看到结果,而后再解释细节这种方法更好一点。建立一个叫http1.go
的文件。而后将下面的代码复制过去:服务器
package main import ( "io" "net/http" ) func hello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Hello world!") } func main() { http.HandleFunc("/", hello) http.ListenAndServe(":8000", nil) }
在终端执行go run http1.go
,而后再浏览器访问http://localhost:8000。你将会看到Hello world!
显示在屏幕上。
为何会这样?在Go语言里全部的可运行的包都必须命名为main
。咱们建立了main和hello两个函数。
在main函数中,咱们从net/http
包中调用了一个http.HandleFucn
函数来注册一个处理函数,在本例中是hello函数。这个函数接受两个参数。第一个是一个字符串,这个将进行路由匹配,在本例中是根路由。第二个函数是一个func (ResponseWriter, Request)
的签名。正如你所见,咱们的hello函数就是这样的签名。下一行中的http.ListenAndServe(":8000", nil)
,表示监听localhost的8000端口,暂时忽略掉nil。函数
在hello函数中咱们有两个参数,一个是http.ResponseWriter
类型的。它相似响应流,其实是一个接口类型。第二个是http.Request
类型,相似于HTTP 请求。咱们没必要使用全部的参数,就想再hello函数中同样。若是咱们想返回“hello world”,那么咱们只须要是用http.ResponseWriter,io.WriteString,是一个帮助函数,将会想输出流写入数据。ui
下面是一个稍微复杂的例子:spa
package main import ( "io" "net/http" ) func hello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Hello world!") } func main() { mux := http.NewServeMux() mux.HandleFunc("/", hello) http.ListenAndServe(":8000", mux) }
在上面这个例子中,咱们不在在函数http.ListenAndServe
使用nil
了。它被*ServeMux
替代了。你可能会猜这个例子跟我上面的例子是样的。使用http注册hanlder 函数模式就是用的ServeMux。
下面是一个更复杂的例子:code
import ( "io" "net/http" ) func hello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Hello world!") } var mux map[string]func(http.ResponseWriter, *http.Request) func main() { server := http.Server{ Addr: ":8000", Handler: &myHandler{}, } mux = make(map[string]func(http.ResponseWriter, *http.Request)) mux["/"] = hello server.ListenAndServe() } type myHandler struct{} func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if h, ok := mux[r.URL.String()]; ok { h(w, r) return } io.WriteString(w, "My server: "+r.URL.String()) }
为了验证你的猜测,咱们有作了相同的事情,就是再次在屏幕上输出Hello world。然而如今咱们没有定义ServeMux,而是使用了http.Server。这样你就能知道为何能够i是用net/http包运行了服务器了。server