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

Request timeout settings for the same domain name are reused #1557

Closed byte0o closed 1 year ago

byte0o commented 1 year ago

fasthttp version: v1.46.0 test code

package main

import (
    "context"
    "fmt"
    "github.com/valyala/fasthttp"
    "net/http"
    "time"
)

func main() {
    go func() {
        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            fmt.Fprintf(w, "hello world")
        })

        http.HandleFunc("/test1", func(w http.ResponseWriter, r *http.Request) {
            time.Sleep(1 * time.Second)
            fmt.Fprintf(w, "Sleep 1 Second")
        })

        http.HandleFunc("/test2", func(w http.ResponseWriter, r *http.Request) {
            time.Sleep(5 * time.Second)
            fmt.Fprintf(w, "Sleep 5 Second")
        })

        http.ListenAndServe(":8000", nil)
    }()

    time.Sleep(1 * time.Second)

    test1()
}

func DoPost(ctx context.Context, ul string, body []byte, deadline time.Time, extractHeader ...string) (err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("panic %v", r)
        }
    }()

    req := fasthttp.AcquireRequest()
    defer fasthttp.ReleaseRequest(req)

    resp := fasthttp.AcquireResponse()
    defer fasthttp.ReleaseResponse(resp)

    req.Header.SetMethod("POST")
    req.SetBody(body)
    req.SetRequestURI(ul)
    if deadline.IsZero() {
        fmt.Println("DO")
        err = fasthttp.Do(req, resp)
    } else {
        //req.SetTimeout(time.Until(deadline))
        fmt.Println("DoDeadline")
        err = fasthttp.DoDeadline(req, resp, deadline)
    }
    if err != nil {
        return
    }
    fmt.Println(string(resp.Body()))
    return
}

func test1() {
    ctx := context.Background()
    er := DoPost(ctx, "http://127.0.0.1:8000/test1", []byte{}, time.Now().Add(5*time.Second))

    fmt.Println(er)
    noDeadline, _ := ctx.Deadline()
    err := DoPost(ctx, "http://127.0.0.1:8000/test2", []byte{}, noDeadline)

    fmt.Println(err)
}

test output: DoDeadline Sleep 1 Second

DO timeout fix pull https://github.com/valyala/fasthttp/pull/1558