Http.Request RequestURI field when executing request in go

I sent a request from the server to []byteand used ReadRequestto request using the method Client.Do. I got an error message:

http: Request.RequestURI cannot be specified in client requests.

Can you explain to me exactly why I got this error?

+4
source share
1 answer

The error is clear: you are not allowed to set RequestURI when executing a client request.

In the documentation for http.Request.RequestURIhe says (my emphasis):

RequestURI - -URI Request-Line (RFC 2616, 5.1),
. URL. HTTP.

, , - , ReadRequest .

, URL- RequestURI, . , , URL , ReadRequest, , ​​ . - URL-, Parse net/url:

- :

package main

import (
    "fmt"
    "strings"
    "bufio"
    "net/http"
    "net/url"
)

var rawRequest = `GET /pkg/net/http/ HTTP/1.1
Host: golang.org
Connection: close
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; de-de) AppleWebKit/523.10.3 (KHTML, like Gecko) Version/3.0.4 Safari/523.10
Accept-Encoding: gzip
Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7
Cache-Control: no-cache
Accept-Language: de,en;q=0.7,en-us;q=0.3

`

func main() {
    b := bufio.NewReader(strings.NewReader(rawRequest))

    req, err := http.ReadRequest(b)
    if err != nil {
        panic(err)
    }

    // We can't have this set. And it only contains "/pkg/net/http/" anyway
    req.RequestURI = ""

    // Since the req.URL will not have all the information set,
    // such as protocol scheme and host, we create a new URL
    u, err := url.Parse("http://golang.org/pkg/net/http/")
    if err != nil {
        panic(err)
    }   
    req.URL = u

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }

    fmt.Printf("%#v\n", resp)
}

Ps. play.golang.org , HTTP-.

+6

All Articles