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
+12.7k Golang : Convert IPv4 address to packed 32-bit binary format
+9k Golang : Apply Histogram Equalization to color images
+12.7k Python : Convert IPv6 address to decimal and back to IPv6
+11.8k Golang : Decompress zlib file example
+6.5k Golang : Check if password length meet the requirement
+11.4k Get form post value in Go
+8.3k Golang : How to check variable or object type during runtime?
+7k Golang : Check if one string(rune) is permutation of another string(rune)
+40.8k Golang : How to count duplicate items in slice/array?
+38.8k Golang : How to iterate over a []string(array)
+10.3k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+5.3k PHP : Fix Call to undefined function curl_init() error