Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 596
Alexander Bauer Avatar asked Nov 07 '12 05:11

Alexander Bauer


People also ask

What is Useragent in request?

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.

What is HTTP Useragent?

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.

How do I set user agent?

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.


1 Answers

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!

like image 74
minikomi Avatar answered Oct 01 '22 13:10

minikomi