您的位置:首页 > 编程语言 > Go语言

使用Go开发web服务器

2016-08-24 17:46 337 查看
原文链接

Go(Golang.org)是在标准库中提供HTTP协议支持的系统语言,通过他可以快速简单的开发一个web服务器。同时,Go语言为开发者提供了很多便利。这本篇博客中我们将列出使用Go开发HTTP 服务器的方式,然后分析下这些不同的方法是如何工作,为什么工作的。

   在开始之前,假设你已经知道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,是一个帮助函数,将会想输出流写入数据。

   下面是一个稍微复杂的例子:

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。
   下面是一个更复杂的例子:

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包运行了服务器了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: