在线文档  >   Golang练习   >   HTTP 服务端

在 go 中,使用 net/http 包编写基本的 HTTP 服务器非常容易。

package main

import (
    "fmt"
    "net/http"
)

// `net/http` 服务器中一个基本的概念是处理程序(handlers)。
// 处理程序是实现 http.Handler 接口的对象。
// 编写处理程序的常用方式是在适当签名的函数上使用 `http.HandlerFunc` 适配器。
func hello(w http.ResponseWriter, req *http.Request) {

    // 函数充当处理程序时,接收 `http.ResponseWriter` 和 `http.Request` 作为参数。 
    // 响应编写器用于填充 HTTP 响应。 在这里我们简单的响应只是 "hello\n"。
    fmt.Fprintf(w, "hello\n")
}

func headers(w http.ResponseWriter, req *http.Request) {

    // 这个处理程序做了一件更复杂的事情,它读取所有的 HTTP 请求头并将它们回显到响应体中。
    for name, headers := range req.Header {
        for _, h := range headers {
            fmt.Fprintf(w, "%v: %v\n", name, h)
        }
    }
}

func main() {

    // 我们使用 `http.HandleFunc` 便捷函数在服务器路由上注册处理程序。
    // 它在 `net/http` 包中设置了 默认路由器 ,并以一个函数作为参数。
    http.HandleFunc("/hello", hello)
    http.HandleFunc("/headers", headers)

    // 最后,我们使用端口和处理程序调用 `ListenAndServe`。 `nil` 告诉它使用我们刚刚设置的默认路由器。
    http.ListenAndServe(":8090", nil)
}

运行结果如下:

# 在后台运行服务器
$ go run http-servers.go &

# 访问 `/hello` 路由。
$ curl localhost:8090/hello
hello