valyala / fasthttp

Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
MIT License
21.94k stars 1.76k forks source link

Bug: fasthttp client connect to Vite dev server on localhost, tcp4 127.0.0.1:5173: connect: connection refused #1730

Closed sixcolors closed 8 months ago

sixcolors commented 8 months ago

Bug Description

When using fasthttp.Client to connect to a Vite/react dev server running on port http://localhost:5173 the connection is refused with the following output Error: The HTTP request failed with error dial tcp4 127.0.0.1:5173: connect: connection refused

How to Reproduce

Clone https://github.com/sixcolors/FiberReactTest

cd frontend
npm install --include=dev && npm run dev

Don't run the main.go from the project but instead run the following:

package main

import (
    "io"
    "log"
    "net/http"

    "github.com/valyala/fasthttp"
)

func main() {
    // test connection to http://localhost:5173
    resp, err := http.Get("http://localhost:5173")
    if err != nil {
        log.Fatalf("Error: The HTTP request failed with error %s", err)
    } else {
        defer resp.Body.Close()
        data, err := io.ReadAll(resp.Body)
        if err != nil {
            log.Fatalf("Error reading body: %v", err)
        }
        log.Printf("HTTP Response Status: %d %s", resp.StatusCode, http.StatusText(resp.StatusCode))
        log.Printf("Response Body: %s", string(data))
    }

    statusCode, body, err := fasthttp.Get(nil, "http://localhost:5173")
    if err != nil {
        log.Fatalf("Error: The HTTP request failed with error %s", err)
    } else {
        log.Printf("HTTP Response Status: %d", statusCode)
        log.Printf("Response Body: %s", body)
    }
}

Expected Behavior

net/http client and fasthttp client both work the same.

Actual result

HTTP Response Status: 200 OK
Response Body: <!doctype html>
...
Error: The HTTP request failed with error dial tcp4 127.0.0.1:5173: connect: connection refused

related to bug report in downstream https://github.com/gofiber/fiber/issues/2890

sixcolors commented 8 months ago

Further info Vite dev server only responds at http://localhost:5173 not http://127.0.0.1:5173 using curl, Safari or Chrome. Consistent with net/http client.

erikdubbelboer commented 8 months ago

This is because vite only listens on IPv6 and fasthttp doesn't try dialing IPv6 by default. If you change the code to this it works:

    client := fasthttp.Client{
        DialDualStack: true,
    }
    statusCode, body, err := client.Get(nil, "http://localhost:5173")