覆盖Go的默认HTTP服务器重定向行为

huangapple go评论96阅读模式
英文:

Overriding Go's default HTTP Sever redirect behaviour

问题

Go的默认HTTP服务器实现会合并HTTP请求中的斜杠,并返回一个HTTP重定向响应到“清理”后的路径:

https://code.google.com/p/go/source/browse/src/pkg/net/http/server.go#1420

所以,如果你发送一个HTTP请求 GET /http://foo.com/,服务器会响应 301 Moved Permanently ... Location: /http:/foo.com/

我想禁用这种行为并自己处理所有路径。

我是一个Go的新手,似乎我可以创建自己的Server实例并覆盖Handler属性,但我不确定如何做到?

英文:

Go's default HTTP server implementation merges slashes in HTTP requests, returning an HTTP redirect response to the "cleaned" path:

https://code.google.com/p/go/source/browse/src/pkg/net/http/server.go#1420

So if you make a HTTP request GET /http://foo.com/, the server responds with 301 Moved Permanently ... Location: /http:/foo.com/.

I'd like to disable this behaviour and handle all paths myself.

I'm a Go newbie, and it seems as if I could create my own Server instance and override the Handler attribute, but I'm not sure how to?

答案1

得分: 10

我想禁用这个行为并自己处理所有路径。

我是一个Go的新手,似乎我可以创建自己的Server实例并覆盖Handler属性,但我不确定如何做?

而不是通过http.Handle或http.HandleFunc方法在http.DefaultServeMux中注册处理程序,只需调用:

http.ListenAndServe(":8080", MyHandler)

其中MyHandler是一个实现了http.Handler接口的类型的实例。

http.ListenAndServe实际上只是一个简写方法,它执行以下操作:

func ListenAndServe(addr string, handler http.Handler) error {
    server := &http.Server{Addr: addr, Handler: handler}
    return server.ListenAndServe()
}

所以你也可以直接这样做。

在你的处理程序中,你可以按照你希望的方式解析/路由URI,像这样:

func (h *MyHandlerType) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    uri := r.URL.Path
    // ...使用uri...
}
英文:

> I'd like to disable this behaviour and handle all paths myself.
>
> I'm a Go newbie, and it seems as if I could create my own Server instance and override the Handler attribute, but I'm not sure how to?

Instead of registering handlers with the http.DefaultServeMux through the http.Handle or http.HandleFunc methods just call:

http.ListenAndServe(":8080", MyHandler)

where MyHandler is an instance of a type that implements the http.Handler interface.

http.ListenAndServe in turn is just a short-hand method that does the following:

func ListenAndServe(addr string, handler http.Handler) error {
    server := &http.Server{Addr: addr, Handler: handler}
    return server.ListenAndServe()
}

so you could do that directly instead as well.

Inside your handler you can then parse/route the URI however you wish like this:

func (h *MyHandlerType) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    uri := r.URL.Path
    // ...use uri...
}

huangapple
  • 本文由 发表于 2013年6月3日 07:34:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/16888285.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定