我一直在研究golang,我注意到很多人使用http.NewServeMux()
函数创建服务器,我真的不明白它是做什么的。
我读到了这个:
在go ServeMux是一个HTTP请求多路复用器。它匹配的URL 针对已注册模式和调用列表的每个传入请求 与该URL最匹配的模式的处理程序。
这与做以下事情有什么不同:
http.ListenAndServe(addr, nil)
http.Handle("/home", home)
http.Handle("/login", login)
使用多路复用的目的是什么?
答案 0 :(得分:4)
来自net/http
GoDoc和来源。
ListenAndServe starts an HTTP server with a given address and handler. The handler is usually nil, which means to use DefaultServeMux. Handle and HandleFunc add handlers to DefaultServeMux
DefaultServeMux
只是预定义的http.ServeMux
var DefaultServeMux = &defaultServeMux
var defaultServeMux ServeMux
您可以在内部看到http.Handle
来电DefaultServeMux
。
func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
http.NewServeMux()
的目的是为您的实例设置http.Servermux
实例,例如当您需要两个http.ListenAndServe函数来侦听具有不同路由的不同端口时。
答案 1 :(得分:2)
Golang中的多路复用器类似于硬件中的多路复用器,它将某些输入乘以某些输出
我给了你一个简单的例子
<table>
<tbody>
<tr>
<td><textarea></textarea></td>
<td>
<div class="scrollable">
this is some really really really really really<br> really really really really really really really<br> really really really really really really really<br> really really really really really really really<br> really really really really really
really really<br> really really really really really really really<br> really really really really really really really<br> really really really really really really really<br> long content
</div>
</td>
</tr>
</tbody>
</table>
给定的多路复用器必须实现type CustomMultiplexer struct {
}
方法才能将http int注册到服务器输入
ServeHTTP
我的func (mux CustomMultiplexer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
SimpleRequestHandler(w, r)
return
}
http.NotFound(w, r)
return
}
是如下方法
SimpleRequestHandler
知道我可以使用我的func SimpleRequestHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
mySimpleGetRequestHandler(w, r)
break
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
break
}
}
在请求的传入之间进行多路复用
CustomMultiplxere
func main() {
customServer := CustomServer{}
err := http.ListenAndServe(":9001", &customServer)
if err != nil {
panic(err)
}
}
方法用作我给定的简单多路复用器。