github.com/blend/go-sdk@v1.20220411.3/webutil/get_host.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  // GetHost returns the request host, omitting the port if specified.
    16  func GetHost(r *http.Request) string {
    17  	if r == nil {
    18  		return ""
    19  	}
    20  	tryHeader := func(key string) (string, bool) {
    21  		return HeaderLastValue(r.Header, key)
    22  	}
    23  	for _, header := range []string{HeaderXForwardedHost} {
    24  		if headerVal, ok := tryHeader(header); ok {
    25  			return headerVal
    26  		}
    27  	}
    28  	if r.URL != nil && len(r.URL.Host) > 0 {
    29  		return r.URL.Host
    30  	}
    31  	if strings.Contains(r.Host, ":") {
    32  		return strings.SplitN(r.Host, ":", 2)[0]
    33  	}
    34  	return r.Host
    35  }
    36  
    37  // GetHostStrict returns the request host, omitting the port if specified,
    38  // and does not consider `X-Forwarded-Host` headers.
    39  func GetHostStrict(r *http.Request) string {
    40  	if r == nil {
    41  		return ""
    42  	}
    43  	if r.Host != "" {
    44  		if strings.Contains(r.Host, ":") {
    45  			return strings.SplitN(r.Host, ":", 2)[0]
    46  		}
    47  		return r.Host
    48  	}
    49  	return ""
    50  }