我想让一个应用程序接口来处理的请求,其中有路径,如http:\\localhost:8080\todo\something,但我需要做的使用自定义服务器。
这是我写的代码片段。
package main
import (
"net/http"
"fmt"
"io"
"time"
)
func myHandler(w http.ResponseWriter, req *http.Request){
io.WriteString(w, "hello, world!\n")
}
func main() {
//Custom http server
s := &http.Server{
Addr: ":8080",
Handler: http.HandlerFunc(myHandler),
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
err := s.ListenAndServe()
if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}受此post启发
我的处理程序接受所有的请求,如http:localhost:8080\abc,http:localhost:8080\abc等如何在自定义服务器中提供路径,以便它只处理与路径匹配的请求。
发布于 2017-01-22 10:50:12
如果你想使用不同的网址路径,你必须创建一些mux,你可以创建一个,使用go提供的默认多路复用器或使用像gorilla这样的第三方多路复用器。
下面的代码是使用提供的标准http库编写的。
func myHandler(w http.ResponseWriter, req *http.Request){
io.WriteString(w, "hello, world!\n")
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/todo/something", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Response"))
})
s := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.ListenAndServe()
}发布于 2020-09-20 19:27:22
补充一下,虽然不推荐,但一个很好的起点是尝试使用std lib附带的DefaultServeMux。当您不向http服务器提供多路复用器时,将使用DefaultServeMux。
func myHandler(w http.ResponseWriter, r *http.Request){
io.WriteString(w, "hello, world!\n")
}
func main(){
// you can register multiple handlers
// as long as it implements the http.Handler interface
http.HandleFunc("/todo/something", myHandler)
http.HandleFunc("/todo/thingTwo", func(w http.ResponseWriter, r *http.Request){
something := strings.TrimPrefix(r.URL.Path, "/todo/")
fmt.Fprintf(w, "We received %s", something)
})
http.ListenAndServe(":5000", nil) //Will use the default ServerMux in place of nil
}这里的想法是,您可以使用默认的服务器多路复用器进行测试,创建自己的多路复用器,就像@Motakjuq使用http.NewServeMux()向您展示的那样,并分配给您的服务器,或者您可以使用第三方路由器库,如go-chi、httprouter,或者简单地从一个很好的集合here中选择,或者简单地查看stdlib
https://stackoverflow.com/questions/41786677
复制相似问题