اتصال هدر
ShouldBindHeader هدرهای درخواست HTTP را مستقیماً با استفاده از تگهای header در struct به آن متصل میکند. این برای استخراج فرادادههایی مانند محدودیت نرخ API، توکنهای احراز هویت، یا هدرهای دامنه سفارشی از درخواستهای ورودی مفید است.
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")}تست
# 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}