Resetting http handlers in golang for unit testing
<p>I'm testing an http server in golang and everything seems pretty smooth except for one annoying thing.</p>

<p>At some point, when I'm configuring the server, before performing a <code>http.ListenAndServe</code> I register an handler with <code>http.Handle("/", myrouter)</code> , the problem is that on the following test, when the configuration method gets called again, I receive the following panic:</p>

<blockquote>
  <p>panic: http: multiple registrations for / [recovered]</p>
</blockquote>

<p>I'd like to run each test in a clean environment, but haven't found a way to tear down <code>http.DefaultServeMux</code>, is there a convenient way for doing this by either "nulling" something or re-configuring the test environment so every test is executed on a fresh environment ?</p>

<hr>

<p><strong>Edit:</strong>
To give some context, as asked, I post here some code and the test I wanted to write, I have to be clear tough on the fact that I'm not even sure on the implementation choices made here (I think I would have configured the server in a slightly different way, but the code's not mine).</p>

<pre><code>package httpserver

import (
    "github.com/gorilla/mux"
    "github.com/private/private/httpserver/rpchandler"
    "net/http"
)

type HTTPServer struct {
    router *mux.Router
    port   int
}

// Config is used to override the default port of the http server.
type Config struct {
    Port *int
}

func NewHTTPServer(config *Config) (*HTTPServer, error) {
    hs := &amp;HTTPServer{
        port: 80,
    }

    // Overwrite default port if passed.
    if config != nil &amp;&amp; config.Port != nil {
        hs.port = *config.Port
    }

    err := hs.router = mux.NewRouter().StrictSlash(false)
    if err != nil {
        return nil, err
    }
    // other mux router configs here...

    http.Handle("/", hs.router)

    return hs, nil
}
</code></pre>

<p>Now, the tests I wanted to write were quite simple, like:</p>

<pre><code>func TestThatServerIsInitializedWithDefaultPort(t *testing.T) {
    sut, _ := NewHTTPServer(nil)

    if sut.port != 80 {
        t.Fatal("default port not configured")
    }

}

func TestThatServerDefaultPortIsOverriddenWithConfig(t *testing.T) {
    mockPort := 8080

    c := Config{
        Port: &amp;mockPort,
    }

    sut, _ := NewHTTPServer(&amp;c)
    if sut.port != 8080 {
        t.Fatal("the port has not been overridden with the one passed in configuration")
    }

}
</code></pre>

<p>However, since I call the handle binding on <code>http</code> twice, I get the panic.</p>