Sobes.tech
Middle+

package main import ( "io" "log" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { go func() { resp, err := http.Get("[link]") if err != nil { log.Println("request error:", err) return } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) w.Write(body) }() } func main() { http.HandleFunc("/proxy", handler) log.Fatal(http.ListenAndServe(":8080", nil)) }

sobes.tech AI

Answer from AI

The provided code has an error: the HTTP request handler launches a goroutine that performs an HTTP request and writes the response to http.ResponseWriter asynchronously. This is incorrect because ResponseWriter is not thread-safe and the request's lifecycle is limited to the handler function.

When the handler function finishes, the connection to the client may be closed, and attempting to write to w from the goroutine can cause a panic or error.

The correct approach is to perform the HTTP request synchronously within the handler and only after receiving the response, write to w:

func handler(w http.ResponseWriter, r *http.Request) {
	resp, err := http.Get("http://example.com")
	if err != nil {
		log.Println("request error:", err)
		w.WriteHeader(http.StatusBadGateway)
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Println("read error:", err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.Write(body)
}

If you need to perform the request asynchronously, you should use other mechanisms, such as WebSocket, or cache the result and send it to the client later, but writing directly to ResponseWriter from a goroutine is not allowed.