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
+9.2k Golang : Timeout example
+7.2k Linux : How to fix Brother HL-1110 printing blank page problem
+12.2k Golang : 2 dimensional array example
+11.1k Golang : How to pipe input data to executing child process?
+19k Golang : Check if directory exist and create if does not exist
+12.7k Golang : Convert IPv4 address to packed 32-bit binary format
+19k Golang : Calculate entire request body length during run time
+6k Golang : Dealing with backquote
+9.6k Golang : interface - when and where to use examples
+10.3k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+13.3k Golang : How to get year, month and day?
+7.6k Golang : Generate human readable password