Files
fasthttp/fasthttpadaptor/request.go
T
Emre Savcı 40eec0b706 byte to string unsafe conversion in fasthttpadaptor ConvertRequest method (#1375)
* add byte to string unsafe conversion to fasthttpadaptor ConvertRequest method()

* add nosec comment line

* Update fasthttpadaptor/request.go

Co-authored-by: Erik Dubbelboer <erik@dubbelboer.com>

* move unsafe package import next to std packages

* fix lint error in test

Co-authored-by: Erik Dubbelboer <erik@dubbelboer.com>
2022-09-15 23:15:26 +03:00

69 lines
1.4 KiB
Go

package fasthttpadaptor
import (
"bytes"
"io"
"net/http"
"net/url"
"unsafe"
"github.com/valyala/fasthttp"
)
// 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.
//
// The http.Request must not be used after the fasthttp handler has returned!
// Memory in use by the http.Request will be reused after your handler has returned!
func ConvertRequest(ctx *fasthttp.RequestCtx, r *http.Request, forServer bool) error {
body := ctx.PostBody()
strRequestURI := b2s(ctx.RequestURI())
rURL, err := url.ParseRequestURI(strRequestURI)
if err != nil {
return err
}
r.Method = b2s(ctx.Method())
r.Proto = "HTTP/1.1"
r.ProtoMajor = 1
r.ProtoMinor = 1
r.ContentLength = int64(len(body))
r.RemoteAddr = ctx.RemoteAddr().String()
r.Host = b2s(ctx.Host())
r.TLS = ctx.TLSConnectionState()
r.Body = io.NopCloser(bytes.NewReader(body))
r.URL = rURL
if forServer {
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)
}
}
ctx.Request.Header.VisitAll(func(k, v []byte) {
sk := b2s(k)
sv := b2s(v)
switch sk {
case "Transfer-Encoding":
r.TransferEncoding = append(r.TransferEncoding, sv)
default:
r.Header.Set(sk, sv)
}
})
return nil
}
func b2s(b []byte) string {
/* #nosec G103 */
return *(*string)(unsafe.Pointer(&b))
}