相对于其他语言的 http service 框架,例如 Node.js 的 Express 和 Python 的 Flask,Go 作为网络C语言提供的 net/http 模块原生支持 http service。
package main
import (
"io"
"net/http"
)
func main() {
http.HandleFunc("/", helloWorldHandler)
http.ListenAndServe(":80", nil)
}
func helloWorldHandler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello world!")
}
Client -> Request -> Multiplexer(Router) -> Handler -> Response -> Client
创建一个http服务,大致需要经历两个过程,首先需要注册路由,即提供url模式和handler函数的映射,其次就是实例化一个server对象,并开启对客户端的监听。