Skip to content

Commit

Permalink
Add Request.TLS and try to avoid a new alloc if Request.Header is alr…
Browse files Browse the repository at this point in the history
…eady allocated (#1034)
  • Loading branch information
Sergio Andrés Virviescas Santana committed May 26, 2021
1 parent b433ecf commit 7d13e18
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions fasthttpadaptor/request.go
Expand Up @@ -12,7 +12,10 @@ import (
// ConvertRequest convert a fasthttp.Request to an http.Request
// forServer should be set to true when the http.Request is going to passed to a http.Handler.
func ConvertRequest(ctx *fasthttp.RequestCtx, r *http.Request, forServer bool) error {
rURL, err := url.ParseRequestURI(string(ctx.RequestURI()))
body := ctx.PostBody()
strRequestURI := string(ctx.RequestURI())

rURL, err := url.ParseRequestURI(strRequestURI)
if err != nil {
return err
}
Expand All @@ -21,28 +24,36 @@ func ConvertRequest(ctx *fasthttp.RequestCtx, r *http.Request, forServer bool) e
r.Proto = "HTTP/1.1"
r.ProtoMajor = 1
r.ProtoMinor = 1
r.ContentLength = int64(len(ctx.PostBody()))
r.ContentLength = int64(len(body))
r.RemoteAddr = ctx.RemoteAddr().String()
r.Host = string(ctx.Host())
r.TLS = ctx.TLSConnectionState()
r.Body = ioutil.NopCloser(bytes.NewReader(body))
r.URL = rURL

if forServer {
r.RequestURI = string(ctx.RequestURI())
r.RequestURI = strRequestURI
}

if r.Header == nil {
r.Header = make(http.Header)
} else if len(r.Header) > 0 {
for k := range r.Header {
delete(r.Header, k)
}
}

hdr := make(http.Header)
ctx.Request.Header.VisitAll(func(k, v []byte) {
sk := string(k)
sv := string(v)

switch sk {
case "Transfer-Encoding":
r.TransferEncoding = append(r.TransferEncoding, sv)
default:
hdr.Set(sk, sv)
r.Header.Set(sk, sv)
}
})

r.Header = hdr
r.Body = ioutil.NopCloser(bytes.NewReader(ctx.PostBody()))
r.URL = rURL
return nil
}

0 comments on commit 7d13e18

Please sign in to comment.