Set UserAgent in http request

Http HeadersGo

Http Headers Problem Overview


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?

Http Headers Solutions


Solution 1 - Http Headers

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexander BauerView Question on Stackoverflow
Solution 1 - Http HeadersminikomiView Answer on Stackoverflow