---
title: "Go: data race in an httptest handler"
category: "code"
id: 5c86f899-cf74-4a20-914f-7ace0e1f838c
canonical: https://solvedlist.com/solutions/go-data-race-in-an-httptest-handler
---

# Go: data race in an httptest handler

> Explains a data race in Go when an httptest handler decodes a request body and the test reads it after HTTP response headers, with a solution using channels for synchronization.

## Question

Why does go test -race report a data race when an httptest handler stores a decoded request body and the test reads it after the HTTP response headers arrive?

## Solution

The handler can keep running after it flushes the response. Pass the decoded value and error through a channel to synchronize the handoff. A buffer of one lets the handler send once without waiting. Save as capture_test.go and run `go test -race capture_test.go`.

```go
package requestcapture

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

func TestRequestBody(t *testing.T) {
	type result struct {
		limit int
		err   error
	}
	captured := make(chan result, 1)
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var body struct {
			Limit int `json:"limit"`
		}
		err := json.NewDecoder(r.Body).Decode(&body)
		w.WriteHeader(http.StatusNoContent)
		w.(http.Flusher).Flush()
		captured <- result{limit: body.Limit, err: err}
	}))
	defer server.Close()

	client := server.Client()
	client.Timeout = 5 * time.Second
	response, err := client.Post(server.URL, "application/json", strings.NewReader(`{"limit":17}`))
	if err != nil {
		t.Fatal(err)
	}
	defer response.Body.Close()

	select {
	case got := <-captured:
		if got.err != nil || got.limit != 17 {
			t.Fatalf("capture = %+v, want limit 17 without error", got)
		}
	case <-time.After(5 * time.Second):
		t.Fatal("handler did not send the request body")
	}
}
```

## Query directly via MCP

```text
POST https://solvedlist.com/mcp
Authorization: Bearer sl_live_…
Content-Type: application/json

{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"solvedlist_lookup","arguments":{"question":"…"}}}
```

Create an API key without an account:

```bash
curl -sS -X POST https://solvedlist.com/api/v1/keys -H 'Content-Type: application/json' -d '{"note":"agent"}'
```

More for agents: https://solvedlist.com/llms.txt and https://solvedlist.com/openapi.json
