Skip to content

Request Headers

Learn how to handle HTTP request headers in Iris.

Reading Headers

go
package main

import "github.com/kataras/iris/v12"

func main() {
    app := iris.New()

    app.Get("/headers", func(ctx iris.Context) {
        // Get single header
        userAgent := ctx.GetHeader("User-Agent")

        // Get multiple headers
        accept := ctx.GetHeader("Accept")
        encoding := ctx.GetHeader("Accept-Encoding")
        language := ctx.GetHeader("Accept-Language")

        ctx.JSON(iris.Map{
            "userAgent": userAgent,
            "accept": accept,
            "encoding": encoding,
            "language": language,
        })
    })

    app.Listen(":8080")
}

Custom Headers

go
app.Get("/custom", func(ctx iris.Context) {
    // Get custom header
    apiKey := ctx.GetHeader("X-API-Key")
    if apiKey == "" {
        ctx.StopWithStatus(iris.StatusUnauthorized)
        return
    }

    ctx.JSON(iris.Map{
        "authenticated": true,
    })
})

Header Existence

go
app.Get("/check", func(ctx iris.Context) {
    hasAuth := ctx.GetHeader("Authorization") != ""
    hasContentType := ctx.GetHeader("Content-Type") != ""

    ctx.JSON(iris.Map{
        "hasAuth": hasAuth,
        "hasContentType": hasContentType,
    })
})

Multiple Values

go
app.Get("/multiple", func(ctx iris.Context) {
    // Get all values for a header
    accepts := ctx.Request().Header["Accept"]

    ctx.JSON(iris.Map{
        "accepts": accepts,
    })
})

Best Practices

  1. Security:

    • Validate headers
    • Check required headers
    • Handle missing headers
    • Sanitize values
    • Monitor suspicious headers
  2. Performance:

    • Cache header values
    • Handle large headers
    • Monitor header size
    • Optimize parsing
    • Clean up resources
  3. Implementation:

    • Use constants
    • Handle case sensitivity
    • Document requirements
    • Follow standards
    • Test edge cases
  4. Maintenance:

    • Monitor usage
    • Update validation
    • Document changes
    • Regular testing
    • Review security

Built with excellence by Hellenic Development, delivering enterprise-grade solutions.