Setting Headers in Go Seems to Fail

I’m messing around with Go’s HTTP package and am sending requests. I’d like to send a user agent header:

package main
import ( "net/http"; "fmt"; "io/ioutil" )

func main() {
	resp, err := http.Get("")
	if err != nil {
         fmt.Println("Error: ", err)
	defer resp.Body.Close()
    resp.Header.Set("User-Agent", "Riverside Rocks")

	for k, v := range resp.Header {
        fmt.Printf("%s: %s\n", k, v)

	body, err := ioutil.ReadAll(resp.Body)
	fmt.Printf("\nResponse Body:\n%s\n", body)

This code works as expected (it returns the HTML of a website), but the user agent is still “go-http-client”. How can I fix this?

This is no an valid user agent!

I believe you can set the user agent to anything.

1 Like

Like this?

resp.Header.Set("User-Agent", "MomRocks/1.0)

Yah there is no such thing as an invalid user agent afaik.


You look like you’re setting a header in the response. I think you’ll have to read up on how to set a header in the request instead.

Agreed, I saw that. I’m just a bit confused as resp is defined at the time of the request.

Not a go coder, but try putting it before you close the response body? Any chance that that finalises and sends the response?