github.com/blend/go-sdk@v1.20220411.3/r2/get_raw_url_parameterized.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 r2
     9  
    10  import (
    11  	"net/http"
    12  	"strings"
    13  )
    14  
    15  // GetRawURLParameterized gets a URL string with named route parameters in place of
    16  // the raw path for a request. Useful for outbound request aggregation for
    17  // metrics and tracing when route parameters are involved.
    18  // Relies on the request's context storing the parameterized path, otherwise will default
    19  // to returning the request `URL`'s `String()`.
    20  func GetRawURLParameterized(req *http.Request) string {
    21  	if req == nil || req.URL == nil {
    22  		return ""
    23  	}
    24  	url := req.URL
    25  	path := GetParameterizedPath(req.Context())
    26  	if path == "" {
    27  		return url.String()
    28  	}
    29  
    30  	// Stripped down version of "net/url" `URL.String()`
    31  	var buf strings.Builder
    32  	if url.Scheme != "" {
    33  		buf.WriteString(url.Scheme)
    34  		buf.WriteByte(':')
    35  	}
    36  	if url.Scheme != "" || url.Host != "" {
    37  		if url.Host != "" || url.Path != "" {
    38  			buf.WriteString("//")
    39  		}
    40  		if host := url.Host; host != "" {
    41  			buf.WriteString(host)
    42  		}
    43  	}
    44  	if !strings.HasPrefix(path, "/") {
    45  		buf.WriteByte('/')
    46  	}
    47  	buf.WriteString(path)
    48  	return buf.String()
    49  }