Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read a header from an http request in golang?

Tags:

go

If I receive a request of type http.Request, how can I read the value of a specific header? In this case I want to pull the value of a jwt token out of the request header.

like image 987
Ayman Elmubark Avatar asked Sep 03 '17 07:09

Ayman Elmubark


People also ask

How do I capture a request header?

You will need to create a Request Attribute for the request headers you want to capture in Settings -> Server-side service monitoring -> Request Attribute. You will have to specify the request attributes you want to capture in the configuration.

What is header in Golang?

A Header represents the key-value pairs in an HTTP header. It's defined as a map where key is of string type and value is an array of string type. type Header map[string][]string.


2 Answers

You can use the r.Header.Get:

func yourHandler(w http.ResponseWriter, r *http.Request) {     ua := r.Header.Get("User-Agent")     ... } 
like image 87
nbari Avatar answered Sep 25 '22 05:09

nbari


package main  import (     "fmt"     "log"     "net/http" )  func main() {     http.HandleFunc("/", handler)     log.Fatal(http.ListenAndServe("localhost:8000", nil)) }  func handler(w http.ResponseWriter, r *http.Request) {     fmt.Fprintf(w, "%s %s %s \n", r.Method, r.URL, r.Proto)     //Iterate over all header fields     for k, v := range r.Header {         fmt.Fprintf(w, "Header field %q, Value %q\n", k, v)     }      fmt.Fprintf(w, "Host = %q\n", r.Host)     fmt.Fprintf(w, "RemoteAddr= %q\n", r.RemoteAddr)     //Get value for a specified token     fmt.Fprintf(w, "\n\nFinding value of \"Accept\" %q", r.Header["Accept"]) } 

Connecting to http://localhost:8000/ from a browser will print the output in the browser.

like image 39
Ravi R Avatar answered Sep 26 '22 05:09

Ravi R