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
+8.9k Golang : Write multiple lines or divide string into multiple lines
+6.9k Golang : Validate credit card example
+10.5k Golang : Command line file upload program to server example
+8.7k Golang : automatically figure out array length(size) with three dots
+8.8k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+8k Golang : Oanda bot with Telegram and RSI example
+23.4k Golang : Fix type interface{} has no field or no methods and type assertions example
+24.1k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+29k Golang : JQuery AJAX post data to server and send data back to client example
+8k Golang : Check if integer is power of four example
+28.9k Golang : missing Git command
+9.8k Golang : Bcrypting password