• 使用Go开发web服务器


    原文链接

    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包运行了服务器了。

  • 相关阅读:
    XML 命名空间
    XML Schema验证
    java 解析XML文档
    Java线程:创建与启动
    CCF-CSP 201312-5 I'm stuck !
    memset函数用法
    C++的字符串多行输入
    OS复习1
    os复习2
    javamail编程2
  • 原文地址:https://www.cnblogs.com/hitandrew/p/5803997.html
Copyright © 2020-2023  润新知