HTTPS redirect

This commit is contained in:
Eduard Urbach 2017-12-02 17:03:36 +01:00
parent e730542c63
commit c5c1c1edaf
2 changed files with 28 additions and 0 deletions

View File

@ -40,6 +40,7 @@ func configure(app *aero.Application) *aero.Application {
middleware.Log(),
middleware.Session(),
middleware.UserInfo(),
middleware.HTTPSRedirect(),
)
// API

View File

@ -0,0 +1,27 @@
package middleware
import (
"fmt"
"strings"
"github.com/aerogo/aero"
)
// HTTPSRedirect middleware redirects to HTTPS if needed.
func HTTPSRedirect() aero.Middleware {
return func(ctx *aero.Context, next func()) {
request := ctx.Request()
userAgent := request.Header().Get("User-Agent")
isBrowser := strings.Contains(userAgent, "Mozilla/") || strings.Contains(userAgent, "Chrome/") || strings.Contains(userAgent, "AppleWebKit/")
if !strings.HasPrefix(request.Protocol(), "HTTP/2") && isBrowser {
fmt.Println("Redirect to HTTPS")
ctx.Redirect("https://" + request.Host() + request.URL().Path)
ctx.Response().WriteHeader(ctx.StatusCode)
return
}
// Handle the request
next()
}
}