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.91k stars 1.76k forks source link

Support default Transport implemention for HostClient #1601

Closed timandy closed 1 year ago

timandy commented 1 year ago

Transport does not provide a default implementation, but after some processing when I implement it myself, I need to call the remaining logic, but the remaining logic contains many private methods. I would like the transport logic to be wrapped into a DefaultTransport for extension.


    if c.Transport != nil {
        err := c.Transport(req, resp)
        return err == nil, err
    }

       // remaining logic
    cc, err := c.acquireConn(req.timeout, req.ConnectionClose())
    if err != nil {
        return false, err
    }
    conn := cc.c

    resp.parseNetConn(conn)

    if c.WriteTimeout > 0 {
        // Set Deadline every time, since golang has fixed the performance issue
        // See https://github.com/golang/go/issues/15133#issuecomment-271571395 for details
        currentTime := time.Now()
        if err = conn.SetWriteDeadline(currentTime.Add(c.WriteTimeout)); err != nil {
            c.closeConn(cc)
            return true, err
        }
    }

My Demo

import (
    "github.com/valyala/fasthttp"
)

func init() {
    client := &fasthttp.Client{
        ConfigureClient: configureClient,
    }
    client.DoTimeout()
}

func configureClient(hc *fasthttp.HostClient) error {
    hc.Transport = Transport{hc: hc}.roundTrip
    return nil
}

type Transport struct {
    hc *fasthttp.HostClient
}

func (t Transport) roundTrip(req *fasthttp.Request, resp *fasthttp.Response) error {
    // my logic add trace-id for all client request
    req.Header.Set("trace-id", xxxx)

    // remain logic
    c := t.hc
    cc, err := c.acquireConn(req.timeout, req.ConnectionClose())
    if err != nil {
        return false, err
    }
    conn := cc.c

    //....

    // print logs after resp
}