Skip to content

Instantly share code, notes, and snippets.

@kenng
Last active December 13, 2023 09:30
Show Gist options
  • Save kenng/286669c70dab08821a7362d6af6ee447 to your computer and use it in GitHub Desktop.
Save kenng/286669c70dab08821a7362d6af6ee447 to your computer and use it in GitHub Desktop.
redirect gin http to https using unrolled/secure
// gin will throw following for the first time due to secure initiate a http.Redirect but gin is unaware of it
// [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 301 with 200
package main
import (
"github.com/gin-gonic/gin"
"github.com/unrolled/secure"
)
func main() {
secureFunc := func() gin.HandlerFunc {
return func(c *gin.Context) {
secureMiddleware := secure.New(secure.Options{
SSLRedirect: true,
SSLHost: "localhost:8888",
})
err := secureMiddleware.Process(c.Writer, c.Request)
// If there was an error, do not continue.
if err != nil {
return
}
c.Next()
}
}()
router := gin.Default()
router.Use(secureFunc)
router.GET("/", func(c *gin.Context) {
c.String(200, "X-Frame-Options header is now `DENY`.")
})
// HTTP
go router.Run(":8066")
router.RunTLS(":8888", "server.pem", "server.key")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment