How to get header data of postman using gin package in golang?

14,726

Solution 1

You can get the token header with c.Request.Header["Token"]. Here is a sample code.

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()
    r.GET("/test", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "token_data": c.Request.Header["Token"],
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}

Here is an example screenshot of postman. Example Screenshot

Solution 2

I use this code and work well

  func getProduct(c *gin.Context) {
        token := strings.Split(c.Request.Header["Authorization"][0], " ")[1]
        c.JSON(200, gin.H{"result": "get product", "token": token})
    }

Here is the test data

GET http://localhost:8081/api/v2/product HTTP/1.1 Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNTg4OTI4NzY0LCJleHAiOjE1ODg5MzM3NjR9.GrPK-7uEsfpdAYamoqaDFclYwTZ3LOlspoEXUORfSuY

Share:
14,726

Related videos on Youtube

Puneet
Author by

Puneet

Updated on June 04, 2022

Comments

  • Puneet
    Puneet almost 2 years

    I want to get the header data using gin package(golang) in the postman but I don't get any idea how to do it. I search it for google but not getting any answer. Can anyone help me to get the data from the postman header the data I want to get is shown in image.

    Image:-

    • Ostap Brehin
      Ostap Brehin about 3 years
      c.GetHeader("token")
  • Puneet
    Puneet about 6 years
    sir @ShivaKishore can we change this data into string?
  • Shiva Kishore
    Shiva Kishore about 6 years
    Here the token is an header. it is defined in go as type Header map[string][]string so for c.Request.Header["Token"] you will get an array of string. if you always send a single value to the token you can access it by c.Request.Header["Token"][0], this will return a string.