Bind header
ShouldBindHeader binds HTTP request headers directly into a struct using header struct tags. This is useful for extracting metadata like API rate limits, authentication tokens, or custom domain headers from incoming requests.
package main
import ( "net/http"
"github.com/gin-gonic/gin")
type testHeader struct { Rate int `header:"Rate"` Domain string `header:"Domain"`}
func main() { r := gin.Default()
r.GET("/", func(c *gin.Context) { h := testHeader{}
if err := c.ShouldBindHeader(&h); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return }
c.JSON(http.StatusOK, gin.H{"Rate": h.Rate, "Domain": h.Domain}) })
r.Run(":8080")}Test it
# Pass custom headerscurl -H "Rate:300" -H "Domain:music" http://localhost:8080/# Output: {"Domain":"music","Rate":300}
# Missing headers -- zero values are usedcurl http://localhost:8080/# Output: {"Domain":"","Rate":0}