← Back to Dashboard
Verified Production Fix

[golang/go] net/http: race condition on windows when using os.File as request body

GH-golang/go#78015 • Mar 07, 2026

### ROOT CAUSE The race condition occurs because multiple goroutines are reading from the same `os.File` concurrently without proper synchronization. The file I/O operations are not thread-safe, leading to interference between concurrent reads. ### CODE FIX To fix the issue, ensure that the file is read in a single goroutine, avoiding concurrent access. Here's how to modify the code:

package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// Create a file
	f, err := os.Create("test.txt")
	if err != nil {
		fmt.Printf("Error creating file: %v\n", err)
		return
	}
	defer f.Close()

	// Write content to the file
	_, err = f.WriteString("Hello, World!")
	if err != nil {
		fmt.Printf("Error writing to file: %v\n", err)
		return
	}

	// Read the file content in a single goroutine
	content, err := io.ReadAll(f)
	if err != nil {
		fmt.Printf("Error reading file: %v\n", err)
		return
	}

	// Create a new request with the file content
	req, err := http.NewRequest("GET", "http://example.com", io.NopCloser(bytes.NewBuffer(content)))
	if err != nil {
		fmt.Printf("Error creating request: %v\n", err)
		return
	}

	// Send the request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Error sending request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// Read and print the response
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Error reading response: %v\n", err)
		return
	}
	fmt.Printf("Response: %s\n", string(respBody))
}


This fix ensures that the file is read in a single goroutine, eliminating the race condition by avoiding concurrent file I/O operations.

Deploy with DigitalOcean

Use this fix in production instantly. Claim your $200 developer credit.

Get Started →