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
+4.1k Golang : Print instead of building pyramids
+17.4k Golang : Example for RSA package functions
+18.4k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+25.2k Golang : Encrypt and decrypt data with AES crypto
+24.1k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+18.4k Golang : Determine if directory is empty with os.File.Readdir() function
+4.5k Javascript : How to loop over and parse JSON data?
+12.4k Golang : Set image canvas or background to transparent
+27.9k Golang : Get first few and last few characters from string
+18.9k Golang : Count number of digits from given integer value
+5.7k Golang : When to use make or new?
+20.8k Golang : How to run Golang application such as web server in the background or as daemon?