ZetCode

Go ServeMux

最后修改时间 2024 年 4 月 11 日

在本文中,我们将展示如何在 Golang 中使用 ServeMux 进行请求路由和分发。

HTTP

超文本传输协议(Hypertext Transfer Protocol (HTTP))是一种用于分布式、协作式、超媒体信息系统的应用层协议。HTTP 协议是万维网数据通信的基础。

ServeMux

ServeMux 是一个 HTTP 请求多路复用器。它用于请求路由和分发。请求路由基于 URL 模式。将匹配最接近 URL 的模式的处理器调用。

Go NewServeMux

NewServeMux 函数分配并返回一个新的 ServeMux。

main.go
package main

import (
    "log"
    "net/http"
    "time"
)

func main() {

    mux := http.NewServeMux()

    now := time.Now()

    mux.HandleFunc("/today", func(rw http.ResponseWriter, _ *http.Request) {

        rw.Write([]byte(now.Format(time.ANSIC)))
    })

    log.Println("Listening...")
    http.ListenAndServe(":3000", mux)
}

该示例创建了一个 HTTP 服务器,它为 /today URL 模式返回当前日期和时间。

mux := http.NewServeMux()

创建了一个新的 ServeMux。

mux.HandleFunc("/today", func(rw http.ResponseWriter, _ *http.Request) {

    rw.Write([]byte(now.Format(time.ANSIC)))
})

使用 HandleFunc 函数将 /today 模式的句柄添加到其中。

http.ListenAndServe(":3000", mux)

创建的多路复用器被传递给 ListenAndServe 函数。

Go DefaultServeMux

DefaultServeMux 只是一个 ServeMux。当我们为 ListenAndServe 方法的第二个参数传递 nil 时,就会使用它。

http.Handlehttp.HandleFunc 全局函数使用 DefaultServeMux 多路复用器。

main.go
package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {

    http.HandleFunc("/", HelloHandler)

    log.Println("Listening...")
    log.Fatal(http.ListenAndServe(":3000", nil))
}

func HelloHandler(w http.ResponseWriter, _ *http.Request) {

    fmt.Fprintf(w, "Hello there!")
}

该示例使用默认多路复用器。

自定义处理器

func (*ServeMux) Handle 函数为给定的模式注册处理器。

http.HandlerFunc 是一个适配器,它将一个具有正确签名的函数转换为 http.Handler

main.go
package main

import (
    "fmt"
    "log"
    "net/http"
)

type helloHandler struct {
}

func (h *helloHandler) ServeHTTP(w http.ResponseWriter, _ *http.Request) {

    fmt.Fprintf(w, "Hello there!")
}

func main() {

    mux := http.NewServeMux()

    hello := &helloHandler{}
    mux.Handle("/hello", hello)

    log.Println("Listening...")
    http.ListenAndServe(":3000", mux)
}

在示例中,我们创建了一个自定义处理器。

type helloHandler struct {
}

声明了一个新类型。

func (h *helloHandler) ServeHTTP(w http.ResponseWriter, _ *http.Request) {

    fmt.Fprintf(w, "Hello there!")
}

要成为处理器,该类型必须实现 ServeHTTP 函数。

hello := &helloHandler{}
mux.Handle("/hello", hello)

我们创建了处理器并将其传递给 Handle 函数。

来源

Go net/http 包 - 参考

在本文中,我们展示了如何使用 ServeMux 在 Go 中进行请求路由和分发。

作者

我的名字是 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。至今,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Go 教程