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?
The User-Agent request header is a characteristic string that lets servers and network peers identify the application, operating system, vendor, and/or version of the requesting user agent.
The HTTP headers User-Agent is a request header that allows a characteristic string that allows network protocol peers to identify the Operating System and Browser of the web-server. Your browser sends the user agent to every website you connect to.
You can use the -A or --user-agent command-line option to pass your own User-Agent string to Curl. By default, Curl sends its own User-Agent string to the server in the following format: "curl/version. number". For example, when you use the Curl tool version 7.54.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With