Search code examples
urlgourlparse

http.NewRequest in golang converting some charterers to % values


go version go1.8.1 windows/amd64

"net/http" package used to build http request.

req, err := http.NewRequest("GET",`http://domain/_api/Web/GetFolderByServerRelativeUrl('` + root_folder_url + `')?$expand=Folders,Files`, nil)

Here if I print url it shows

http://domain/_api/Web/GetFolderByServerRelativeUrl%28%27rooturl%27%29?$expand=Folders,Files

Not understanding why url parser is replacing ' to %27 here. Whereas I need ' to be sent as is while requesting.


Solution

  • The http.NewRequest function calls url.Parse to set the Request.URL. The URL.RequestURI method is called to get the request URI written to the network.

    An application can override any transformation made by Parse/RequestURI by setting the request URL Opaque field:

    req, err := http.NewRequest("GET", "http://domain/", nil)
    if err != nil {
       // handle error
    }
    req.URL.Opaque = `/_api/Web/GetFolderByServerRelativeUrl('` + root_folder_url + `')?$expand=Folders,Files`
    

    In this snippet, the argument to NewRequest specifies the protocol and host for the request. The opaque value specifies the request URI written to the network. The request URI does not include host or protocol.