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.
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
Related videos on Youtube
Author by
Puneet
Updated on June 04, 2022Comments
-
Puneet almost 2 years
I want to get the
header
data usinggin
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 postmanheader
the data I want to get is shown in image.-
Ostap Brehin about 3 years
c.GetHeader("token")
-
-
Puneet about 6 yearssir @ShivaKishore can we change this data into string?
-
Shiva Kishore about 6 yearsHere the token is an header. it is defined in go as
type Header map[string][]string
so forc.Request.Header["Token"]
you will get an array ofstring
. if you always send a single value to the token you can access it byc.Request.Header["Token"][0]
, this will return a string.