So, I've just started with Go and I'm trying to learn HTTP
package. I found this program on the internet
headers := make(map[string]string)
headers["authorization"] = "1432536546" //the auhorization string
url := "anUrl\"
req, err := http.NewRequest("DELETE", url, headers)
if err != nil {
panic(err)
}
But it is wrong, as it appears you can't use maps like this as they don't implement the io.Reader
interface:
cannot use headers (type map[string]string) as type io.Reader in argument to http.NewRequest:
map[string]string does not implement io.Reader (missing Read method)
This is one of the first code snippets I tried, I actually got it from what I thought to be a reliable source, and obviously it doesn't compile. Go looks pretty interesting, but it has pretty much zero tutorials and useful documentation... Please help me, what is the right way to do it?
The third parameter is Body, which is used in POST requests. It is not for headers. To add headers,
req, err := http.NewRequest("DELETE", url, nil)
if err != nil{
panic(err);
}
req.Header.Add("Authorization","1432536546") //string, string
The Go documentation does provide several examples. This one is the first example in the Overview
section.
Your assumption is correct, you can't use the NewRequest
method from the net/http
package in that way.
Moreover, it doesn't make a lot of sense as the third parameter of the NewRequest
function is supposed to be the body payload of the request, not the headers.
func NewRequest(method, urlStr string, body io.Reader) (*Request, error)
Assuming the library is not incorrect, My assumption is that the http
package here is not the net/http
package, rather some sort of other HTTP client that is imported as http
. In fact, if you import
import (
"github.com/foobar/someclient/http"
)
it will also be referenced as http
. You should check the import of the file.
FYI, the correct way to add headers is:
req, err := http.NewRequest("DELETE", "/path/to/something", nil)
if err != nil {
// do something
}
req.Header.Add("authorization", "1432536546")