GoServeMux教程展示了如何使用ServeMux在Golang中进行请求路由和调度。
$ go version go version go1.18.1 linux/amd64
我们使用Go版本1.18。
HTTP
超文本传输协议(HTTP)是分布式、协作、超媒体信息系统的应用协议。HTTP协议是万维网数据通信的基础。
ServeMux
ServeMux是一个HTTP请求多路复用器。它用于请求路由和调度。请求路由基于URL模式。每个传入请求的URL都与注册模式列表相匹配。调用最适合URL的模式的处理程序。
去NewServeMux
NewServeMux
函数分配并返回一个新的ServeMux。
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
函数。
去DefaultServeMux
DefaultServeMux
只是一个ServeMux。当我们将nil
传递给第二个参数的ListenAndServe
方法时使用它。
http.Handle
和http.HandleFunc
全局函数使用DefaultServeMux
多路复用器。
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
。
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
函数。
在本教程中,我们展示了如何使用ServeMux进行请求路由和调度inGo。
列出所有Go教程。