Commit 7e7f8993 authored by Brad Fitzpatrick's avatar Brad Fitzpatrick

net/http: parse Request-Line in a function, remove an allocation

Removes another per-request allocation. Also makes the code more
readable, IMO. And more testable.

benchmark                                   old ns/op    new ns/op    delta
BenchmarkServerFakeConnWithKeepAliveLite        10539        10324   -2.04%

benchmark                                  old allocs   new allocs    delta
BenchmarkServerFakeConnWithKeepAliveLite           20           19   -5.00%

benchmark                                   old bytes    new bytes    delta
BenchmarkServerFakeConnWithKeepAliveLite         1609         1559   -3.11%

R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/8118044
parent 731dcb76
...@@ -467,6 +467,17 @@ func (r *Request) SetBasicAuth(username, password string) { ...@@ -467,6 +467,17 @@ func (r *Request) SetBasicAuth(username, password string) {
r.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(s))) r.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(s)))
} }
// parseRequestLine parses "GET /foo HTTP/1.1" into its three parts.
func parseRequestLine(line string) (method, requestURI, proto string, ok bool) {
s1 := strings.Index(line, " ")
s2 := strings.Index(line[s1+1:], " ")
if s1 < 0 || s2 < 0 {
return
}
s2 += s1 + 1
return line[:s1], line[s1+1 : s2], line[s2+1:], true
}
// ReadRequest reads and parses a request from b. // ReadRequest reads and parses a request from b.
func ReadRequest(b *bufio.Reader) (req *Request, err error) { func ReadRequest(b *bufio.Reader) (req *Request, err error) {
...@@ -484,13 +495,12 @@ func ReadRequest(b *bufio.Reader) (req *Request, err error) { ...@@ -484,13 +495,12 @@ func ReadRequest(b *bufio.Reader) (req *Request, err error) {
} }
}() }()
var f []string var ok bool
if f = strings.SplitN(s, " ", 3); len(f) < 3 { req.Method, req.RequestURI, req.Proto, ok = parseRequestLine(s)
if !ok {
return nil, &badStringError{"malformed HTTP request", s} return nil, &badStringError{"malformed HTTP request", s}
} }
req.Method, req.RequestURI, req.Proto = f[0], f[1], f[2]
rawurl := req.RequestURI rawurl := req.RequestURI
var ok bool
if req.ProtoMajor, req.ProtoMinor, ok = ParseHTTPVersion(req.Proto); !ok { if req.ProtoMajor, req.ProtoMinor, ok = ParseHTTPVersion(req.Proto); !ok {
return nil, &badStringError{"malformed HTTP version", req.Proto} return nil, &badStringError{"malformed HTTP version", req.Proto}
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment