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
+29.2k Golang : Save map/struct to JSON or XML file
+17.5k Golang : Defer function inside init()
+11.1k Golang : Calculate Relative Strength Index(RSI) example
+6.7k Golang : Join lines with certain suffix symbol example
+9.6k Golang : Detect number of active displays and the display's resolution
+27.2k Golang : Convert CSV data to JSON format and save to file
+11.6k Golang : Calculations using complex numbers example
+6.3k CodeIgniter : form input set_value cause " to become & quot
+6.1k Golang : Scan forex opportunities by Bollinger bands
+14.9k Golang : package is not in GOROOT during compilation
+7.2k Golang : Not able to grep log.Println() output
+9k Golang : Intercept and compare HTTP response code example