How to get header data of postman using gin package in golang
Asked Answered
L

3

9

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:-

Locket answered 19/4, 2018 at 5:22 Comment(1)
c.GetHeader("token")Grantley
P
17

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

Prendergast answered 19/4, 2018 at 5:34 Comment(2)
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
P
6

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

Pich answered 10/9, 2020 at 1:30 Comment(0)
L
5

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
}
Lavettelavigne answered 12/11, 2022 at 16:33 Comment(1)
Much more elegant solution.Demott

© 2022 - 2024 — McMap. All rights reserved.