Golang : Get and Set User-Agent examples
Problem :
You want to detect User-Agent of your web application users and also setup your own User-Agent name for your Golang application.
How to get and set User-Agent in Golang application?
Solution :
Example 1 :
package main
import (
"fmt"
"net/http"
)
func getUserAgent(w http.ResponseWriter, r *http.Request) {
ua := r.Header.Get("User-Agent")
fmt.Printf("user agent is: %s \n", ua)
w.Write([]byte("user agent is " + ua))
}
func main() {
http.HandleFunc("/", getUserAgent)
http.ListenAndServe(":8080", nil)
}
Example 2:
package main
import (
"fmt"
"net/http"
)
func getUserAgent(w http.ResponseWriter, r *http.Request) {
ua := r.UserAgent() //<---- simpler and faster!
fmt.Printf("user agent is: %s \n", ua)
w.Write([]byte("user agent is " + ua))
}
func main() {
http.HandleFunc("/", getUserAgent)
http.ListenAndServe(":8080", nil)
}
To set User-Agent for your Golang application, first create a client and set client's request header with [your user-agent name] before executing the request.
For instance :
client := &http.Client{}
request, err := http.NewRequest("GET", "http://example.com", nil)
if err != nil {
log.Fatalln(err)
}
request.Header.Set("User-Agent", "[your user-agent name]")
resp, err := client.Do(req)
The web site example.com will detect your program User-Agent as whatever name you choose for [your user-agent name].
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.7k Get Facebook friends working in same company
+17.5k Convert JSON to CSV in Golang
+33.5k Golang : All update packages with go get command
+25.6k Golang : missing Mercurial command
+5.7k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+9.3k Golang : Accessing content anonymously with Tor
+6.4k Golang : Combine slices of complex numbers and operation example
+16.3k CodeIgniter/PHP : Create directory if does not exist example
+13.5k Golang : Activate web camera and broadcast out base64 encoded images
+8.9k Golang : How to use Gorilla webtoolkit context package properly
+7.3k Golang : Convert source code to assembly language
+6.7k Mac/Linux/Windows : Get CPU information from command line