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?
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With