ginhelmet

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 28, 2025 License: MIT Imports: 2 Imported by: 71

README

gin-helmet

A modular security middleware collection for Go web frameworks, inspired by helmet.js.

Overview

This package provides HTTP security middleware for multiple Go web frameworks through a core abstraction layer. Each framework has its own implementation package that wraps the core functionality.

Architecture

  • core/ - Framework-agnostic security middleware logic
  • ginhelmet/ - Gin framework implementation
  • echohelmet/ - Echo framework implementation
  • beegohelmet/ - Beego framework implementation
  • zerohelmet/ - Go-Zero framework implementation
  • fiberhelmet/ - Fiber framework implementation

Supported Frameworks

Framework Package Usage
Gin ginhelmet go get github.com/danielkov/gin-helmet/ginhelmet
Echo echohelmet go get github.com/danielkov/gin-helmet/echohelmet
Beego beegohelmet go get github.com/danielkov/gin-helmet/beegohelmet
Go-Zero zerohelmet go get github.com/danielkov/gin-helmet/zerohelmet
Fiber fiberhelmet go get github.com/danielkov/gin-helmet/fiberhelmet

Quick Start

Gin Example
package main

import (
    "github.com/gin-gonic/gin"
    "github.com/danielkov/gin-helmet/ginhelmet"
)

func main() {
    r := gin.Default()

    // Use default security headers
    r.Use(ginhelmet.Default())

    // Or use individual middleware
    r.Use(ginhelmet.NoSniff())
    r.Use(ginhelmet.FrameGuard())

    r.GET("/", func(c *gin.Context) {
        c.JSON(200, gin.H{"message": "Hello, World!"})
    })

    r.Run()
}
Echo Example
package main

import (
    "github.com/labstack/echo/v4"
    "github.com/danielkov/gin-helmet/echohelmet"
)

func main() {
    e := echo.New()

    // Use default security headers
    for _, middleware := range echohelmet.Default() {
        e.Use(middleware)
    }

    e.GET("/", func(c echo.Context) error {
        return c.JSON(200, map[string]string{"message": "Hello, World!"})
    })

    e.Start(":8080")
}
Fiber Example
package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/danielkov/gin-helmet/fiberhelmet"
)

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

    // Use default security headers
    for _, middleware := range fiberhelmet.Default() {
        app.Use(middleware)
    }

    app.Get("/", func(c *fiber.Ctx) error {
        return c.JSON(fiber.Map{"message": "Hello, World!"})
    })

    app.Listen(":8080")
}

Available Middleware

All implementations provide the same security middleware functions:

  • NoSniff() - Prevents MIME type sniffing
  • DNSPrefetchControl() - Controls DNS prefetching
  • FrameGuard() - Prevents clickjacking
  • SetHSTS() - Enforces HTTPS connections
  • IENoOpen() - Prevents IE from executing downloads
  • XSSFilter() - Basic XSS protection (deprecated, use CSP instead)
  • Referrer() - Controls referrer information
  • NoCache() - Disables caching
  • ContentSecurityPolicy() - Sets Content Security Policy
  • ExpectCT() - Certificate Transparency (deprecated)
  • SetHPKP() - HTTP Public Key Pinning (deprecated)
  • CrossOriginOpenerPolicy() - COOP header
  • CrossOriginEmbedderPolicy() - COEP header
  • CrossOriginResourcePolicy() - CORP header
  • PermissionsPolicy() - Controls browser features
  • ClearSiteData() - Clears browser data
  • Default() - Applies recommended security headers

Content Security Policy Example

// Gin
r.Use(ginhelmet.ContentSecurityPolicy(
    ginhelmet.CSP("default-src", "'self'"),
    ginhelmet.CSP("img-src", "*"),
    ginhelmet.CSP("script-src", "'self' 'unsafe-inline'"),
))

// Echo
e.Use(echohelmet.ContentSecurityPolicy(
    echohelmet.CSP("default-src", "'self'"),
    echohelmet.CSP("img-src", "*"),
    echohelmet.CSP("script-src", "'self' 'unsafe-inline'"),
))

Benefits

  • No Framework Lock-in: The core package has no framework dependencies
  • Consistent API: Same function names and behavior across all frameworks
  • Minimal Dependencies: Each framework package only pulls in what it needs
  • Easy Migration: Switch between frameworks without changing security logic
  • Type Safety: Full Go type safety and IDE support

Writing Your Own Framework-Specific Helmet Adapter

// MyHeaderWriter implements core.HeaderWriter for My framework contexts
type MyHeaderWriter struct {
	ctx myframework.Context
}

// SetHeader sets a header in the response - adopt this to your framework's context
func (m *MyHeaderWriter) SetHeader(key, value string) {
	m.ctx.Response().Header().Set(key, value)
}

// Next is called when the middleware is done - adopt this to your framework's context
func (m *MyHeaderWriter) Next() {
	m.ctx.Next()
}

// wrapMiddleware converts a core.MiddlewareFunc to myframework.MiddlewareFunc
func wrapMiddleware(middleware core.MiddlewareFunc) myframework.MiddlewareFunc {
	return func(next myframework.HandlerFunc) myframework.HandlerFunc {
		return func(c myframework.Context) error {
			writer := &MyHeaderWriter{ctx: c}
			middleware(writer)
			return next(c)
		}
	}
}

// You can copy/paste all of the functions from any of the existing framework-specific packages, e.g.: [echohelmet/helmet.go](echohelmet/helmet.go#L32)
// NoRobotIndex applies header to protect your server from robot indexation
func NoRobotIndex() BeegoMiddleware {
	return wrapMiddleware(core.NoRobotIndex())
}

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package ginhelmet provides security middleware for Gin web framework.

Deprecated: This package is deprecated. Please use github.com/danielkov/gin-helmet/ginhelmet instead. This package is maintained for backwards compatibility only.

Migration example:

Old: import "github.com/danielkov/gin-helmet"
New: import "github.com/danielkov/gin-helmet/ginhelmet"

All function calls remain the same, just change the import path.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CSP deprecated

func CSP(key, value string) string

CSP is a helper function for building Content Security Policy directives.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.CSP instead.

func ClearSiteData deprecated

func ClearSiteData(types ...string) gin.HandlerFunc

ClearSiteData clears specific types of data from the browser.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.ClearSiteData instead.

func ContentSecurityPolicy deprecated

func ContentSecurityPolicy(opts ...string) gin.HandlerFunc

ContentSecurityPolicy sets a header which will restrict your browser to only allow certain sources for assets on your website. The function accepts a map of its parameters which are appended to the header so you can control which headers should be set.

Example usage:

s.Use(ginhelmet.ContentSecurityPolicy(
	ginhelmet.CSP("default-src", "'self'"),
	ginhelmet.CSP("img-src", "*"),
	ginhelmet.CSP("media-src", "media1.com media2.com"),
	ginhelmet.CSP("script-src", "userscripts.example.com"),
))

See [Content Security Policy on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) for more info.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.ContentSecurityPolicy instead.

func ContentSecurityPolicyLegacy deprecated

func ContentSecurityPolicyLegacy(opts ...string) gin.HandlerFunc

ContentSecurityPolicyLegacy sets CSP header with legacy browser support.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.ContentSecurityPolicyLegacy instead.

func CrossOriginEmbedderPolicy deprecated

func CrossOriginEmbedderPolicy(opt ...string) gin.HandlerFunc

CrossOriginEmbedderPolicy (COEP) helps isolate your document from other origins.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.CrossOriginEmbedderPolicy instead.

func CrossOriginOpenerPolicy deprecated

func CrossOriginOpenerPolicy(opt ...string) gin.HandlerFunc

CrossOriginOpenerPolicy (COOP) helps isolate your document from other origins.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.CrossOriginOpenerPolicy instead.

func CrossOriginResourcePolicy deprecated

func CrossOriginResourcePolicy(opt ...string) gin.HandlerFunc

CrossOriginResourcePolicy (CORP) helps isolate your document from other origins.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.CrossOriginResourcePolicy instead.

func DNSPrefetchControl deprecated

func DNSPrefetchControl() gin.HandlerFunc

DNSPrefetchControl sets Prefetch Control header to prevent browser from prefetching DNS.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.DNSPrefetchControl instead.

func Default deprecated

Default returns a number of handlers that are advised to use for basic HTTP(s) protection.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.Default instead.

func ExpectCT deprecated

func ExpectCT(maxAge int, enforce bool, reportURI ...string) gin.HandlerFunc

ExpectCT sets Certificate Transparency header which can enforce that you're using a Certificate which is ready for the upcoming Chrome requirements policy. The function accepts a maxAge int which is the TTL for the policy in delta seconds, an enforce boolean, which simply adds an enforce directive to the policy (otherwise it's report-only mode) and a optional reportUri, which is the URI to which report information is sent when the policy is violated. NOTE: Expect-CT is deprecated as of June 2021.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.ExpectCT instead.

func FrameGuard deprecated

func FrameGuard(opt ...string) gin.HandlerFunc

FrameGuard sets Frame Options header to deny to prevent content from the website to be served in an iframe.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.FrameGuard instead.

func IENoOpen deprecated

func IENoOpen() gin.HandlerFunc

IENoOpen sets Download Options header for Internet Explorer to prevent it from executing downloads in the site's context.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.IENoOpen instead.

func NoCache deprecated

func NoCache() gin.HandlerFunc

NoCache obliterates cache options by setting a number of headers. This prevents the browser from storing your assets in cache.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.NoCache instead.

func NoRobotIndex deprecated

func NoRobotIndex() gin.HandlerFunc

NoRobotIndex applies header to protect your server from robot indexation.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.NoRobotIndex instead.

func NoSniff deprecated

func NoSniff() gin.HandlerFunc

NoSniff applies header to protect your server from MimeType Sniffing.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.NoSniff instead.

func PermissionsPolicy deprecated

func PermissionsPolicy(policy string) gin.HandlerFunc

PermissionsPolicy sets the Permissions Policy header to control which browser features can be used.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.PermissionsPolicy instead.

func Referrer deprecated

func Referrer(opt ...string) gin.HandlerFunc

Referrer sets the Referrer Policy header to prevent the browser from sending data from your website to another one upon navigation an optional string can be provided to set the policy to something else other than "strict-origin-when-cross-origin".

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.Referrer instead.

func SetHPKP deprecated

func SetHPKP(keys []string, maxAge int, sub bool, reportURI ...string) gin.HandlerFunc

SetHPKP sets HTTP Public Key Pinning for your server. It is not necessarily a great thing to set this without proper knowledge of what this does. [Read here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning) otherwise you may likely end up DoS-ing your own server and domain. The function accepts a map of directives and their values according to specifications. NOTE: HPKP is deprecated and not recommended for use.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.SetHPKP instead.

func SetHSTS deprecated

func SetHSTS(sub bool, opt ...int) gin.HandlerFunc

SetHSTS Sets Strict Transport Security header to the default of 60 days an optional integer may be added as a parameter to set the amount in seconds.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.SetHSTS instead.

func XSSFilter deprecated

func XSSFilter() gin.HandlerFunc

XSSFilter applies very minimal XSS protection via setting the XSS Protection header on. NOTE: X-XSS-Protection is deprecated. Use Content Security Policy instead.

Deprecated: Use github.com/danielkov/gin-helmet/ginhelmet.XSSFilter instead.

Types

This section is empty.

Directories

Path Synopsis
core module
echohelmet module
ginhelmet module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL