Testing Go HTTP logic with go-httpbin

Ahmet Alp Balkan
, on

If you ever found yourself writing a piece of code doing a HTTP POST request and then trying to test it with a real HTTP server, you might have heard of httpbin.org. It offers HTTP endpoints that help you test your client logic, by echoing the headers and other data you sent to it, or by returning a response with the status code you want, among many other things.

Bad thing about httpbin.org is, you don’t really want to use it in your test suite. It is an external dependency. As with all external dependencies, you simply don’t know if your code will outlive httpbin.org.

This is why I wrote go-httpbin. It is a httpbin.org clone written in Go which provides you an in-memory server with the endpoints you like from httpbin.org. You can start it from your Go test code efficiently and clean it up effortlessly.

With go-httpbin you can easily combine Go’s net/http/httptest package and write powerful tests by starting ephemeral HTTP servers.

Here is a test case, harnessing the Download() method you implemented by downloading 64kb of data from httpbin endpoint locally by requesting /bytes/65536. Once the test is done, the server is disposed:

func TestDownload(t *testing.T) {
    api := httpbin.GetMux()
    server := httptest.NewServer()
    defer server.Close()

    data, err := Download(server.URL + "/bytes/65536")
    if err != nil {
        t.Fatal(err)
    }
    if len(data) != 65536 {
        t.Fatal("got wrong data length from Download()")
    }
}

Or, if you request /image/png you can get a lovely picture like this:

I would love to hear what you think of this project. Feel free to open issues on the GitHub repository.

Happy testing!


If you liked this post, you can follow me on Twitter or subscribe by email to my blog (no more than an article/month).