Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Go's default HTTP Sever redirect behaviour

Tags:

http

go

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?

like image 997
jb. Avatar asked Dec 27 '22 02:12

jb.


1 Answers

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...
}
like image 109
thwd Avatar answered Jan 15 '23 18:01

thwd