go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/apputil/upgrade_https.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package apputil
     9  
    10  import (
    11  	"strings"
    12  
    13  	"go.charczuk.com/sdk/web"
    14  )
    15  
    16  // UpgradeHTTPS upgrades http connections to https with a redirect in typical settings.
    17  //
    18  // We do so through `X-Forwarded-Proto` header sniffs because many reverse-proxy hosted services
    19  // forward all traffic to http and add forwarded headers so we know what the context
    20  // of the original request was.
    21  //
    22  // Normally we'd run a second http server on 80 (in addition to 443) and do this redirect,
    23  // but because of the specific nature of how many systems host "https" services on http ports
    24  // this is what we need to do.
    25  func UpgradeHTTPS(action web.Action) web.Action {
    26  	return func(ctx web.Context) web.Result {
    27  		if strings.EqualFold(ctx.Request().Header.Get(web.HeaderXForwardedProto), "http") {
    28  			web.RedirectUpgrade(ctx.Response(), ctx.Request())
    29  			return nil
    30  		}
    31  		return action(ctx)
    32  	}
    33  }