Golang : How to get HTTP request header information?
Alright, as a webmaster sometimes we want to know about our visitors and then alert us if there is any visitor that match certain profile.
For example, we want to know where the visitor from and which client he/she or it(bot) is using. Fortunately, HTTP request header will provide us the information we want with header fields - RemoteAddr
and User-Agent
. If the IP address was banned by you, then tell your server to do something about it.
This code example below will demonstrate how to retrieve the HTTP request header information such as this :
{
"Method": "GET",
"URL": {
"Scheme": "",
"Opaque": "",
"User": null,
"Host": "",
"Path": "/favicon.ico",
"RawQuery": "",
"Fragment": ""
},
"Proto": "HTTP/1.1",
"ProtoMajor": 1,
"ProtoMinor": 1,
"Header": {
"Accept": [
"*/*"
],
"Accept-Encoding": [
"gzip, deflate, sdch"
],
"Accept-Language": [
"en-US,en;q=0.8"
],
"Connection": [
"keep-alive"
],
"Cookie": [
"__utma=72123530.124214442.1438251812.1438251812.1438274470.2; __utmc=72123530; __utmz=72123530.1438251812.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)"
],
"User-Agent": [
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36"
]
},
"Body": {
"Closer": {
"Reader": null
}
},
"ContentLength": 0,
"TransferEncoding": null,
"Close": false,
"Host": "example.com:8080",
"Form": null,
"PostForm": null,
"MultipartForm": null,
"Trailer": null,
"RemoteAddr": "121.122.88.158:65075",
"RequestURI": "/favicon.ico",
"TLS": null
}
and output the result in JSON format to terminal and web page.
package main
import (
"fmt"
"net/http"
"encoding/json"
)
func Home(w http.ResponseWriter, r *http.Request) {
// out JSON format
// see - https://www.socketloop.com/tutorials/golang-http-response-json-encoded-data
byte, err := json.Marshal(r)
if err != nil {
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, string(byte))
fmt.Println(string(byte))
}
func main() {
http.HandleFunc("/", Home)
http.ListenAndServe(":8080", nil)
}
run this code and point your browser to the main page. You should be able to see the JSON formatted HTTP request header result about your visitor.
What if you want to extract User-Agent
only?
Then narrow down to the field you want to extract to
r.Header.Get("User-Agent")
For example :
package main
import (
"fmt"
"net/http"
"encoding/json"
)
func Home(w http.ResponseWriter, r *http.Request) {
// out JSON format
// see - https://www.socketloop.com/tutorials/golang-http-response-json-encoded-data
byte, err := json.Marshal(r.Header.Get("User-Agent")) // <-------- here !
if err != nil {
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, string(byte))
fmt.Println(string(byte))
}
func main() {
http.HandleFunc("/", Home)
http.ListenAndServe(":8080", nil)
}
References :
https://www.socketloop.com/tutorials/get-client-ip-address
https://www.socketloop.com/tutorials/golang-http-response-json-encoded-data
See also : Golang : HTTP response JSON encoded data
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.8k Golang : Of hash table and hash map
+30.4k error: trying to remove "yum", which is protected
+14.6k Golang : How to check if IP address is in range
+22.4k Golang : Calculate time different
+24.8k Golang : Convert uint value to string type
+4.7k Python : Convert(cast) bytes to string example
+8k Golang: Prevent over writing file with md5 hash
+10k Android Studio : Simple input textbox and intercept key example
+8.7k Golang : Apply Histogram Equalization to color images
+5.6k Golang : Extract unicode string from another unicode string example
+27.8k Get file path of temporary file in Go
+6.7k CloudFlare : Another way to get visitor's real IP address