github.com/blend/go-sdk@v1.20220411.3/webutil/get_proto.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package webutil
     9  
    10  import (
    11  	"net/http"
    12  	"strings"
    13  )
    14  
    15  // GetProto gets the request proto.
    16  // X-FORWARDED-PROTO is checked first, then the original request proto is used.
    17  func GetProto(r *http.Request) (scheme string) {
    18  	if r == nil {
    19  		return
    20  	}
    21  
    22  	// Retrieve the scheme from X-Forwarded-Proto.
    23  	if proto, ok := HeaderLastValue(r.Header, HeaderXForwardedProto); ok {
    24  		scheme = strings.ToLower(proto)
    25  	} else if proto, ok = HeaderLastValue(r.Header, HeaderXForwardedScheme); ok {
    26  		scheme = strings.ToLower(proto)
    27  	} else if proto, ok = HeaderLastValue(r.Header, HeaderForwarded); ok {
    28  		// match should contain at least two elements if the protocol was
    29  		// specified in the Forwarded header. The first element will always be
    30  		// the 'proto=' capture, which we ignore. In the case of multiple proto
    31  		// parameters (invalid) we only extract the first.
    32  		if match := protoRegex.FindStringSubmatch(proto); len(match) > 1 {
    33  			scheme = strings.ToLower(match[1])
    34  		}
    35  	} else if r.URL != nil {
    36  		scheme = strings.ToLower(r.URL.Scheme)
    37  	}
    38  	return
    39  }