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.
How to get header data of postman using gin package in golang
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
}
sir @ShivaKishore can we change this data into string? –
Locket
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. –
Prendergast 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
Instead of accessing request object directly, gin provides a getter (easier to use and makes code cleaner). Based on @Shiva accepted answer:
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{
// or c.GetHeader("Authorization")
"token_data": c.GetHeader("Token"),
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}
Much more elegant solution. –
Demott
© 2022 - 2024 — McMap. All rights reserved.
c.GetHeader("token")
– Grantley