Set UserAgent in http request
I'm trying to make my Go application specify itself as a specific UserAgent
, but can't find anything on how to go about doing this with net/http
. I'm creating an http.Client
, and using it to make Get
requests, via client.Get()
.
Is there a way to set the UserAgent
in the Client, or at all?
Solution 1:
When creating your request use request.Header.Set("key", "value")
:
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
client := &http.Client{}
req, err := http.NewRequest("GET", "http://httpbin.org/user-agent", nil)
if err != nil {
log.Fatalln(err)
}
req.Header.Set("User-Agent", "Golang_Spider_Bot/3.0")
resp, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
log.Println(string(body))
}
Result:
2012/11/07 15:05:47 {
"user-agent": "Golang_Spider_Bot/3.0"
}
P.S. http://httpbin.org is amazing for testing this kind of thing!