github.com/blend/go-sdk@v1.20240719.1/r2/get_raw_url_parameterized.go (about)

     1  /*
     2  
     3  Copyright (c) 2024 - 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  	"fmt"
    12  	"net/http"
    13  	"strings"
    14  )
    15  
    16  // GetRawURLParameterized gets a URL string with named route parameters in place of
    17  // the raw path for a request. Useful for outbound request aggregation for
    18  // metrics and tracing when route parameters are involved.
    19  // Relies on the request's context storing the optional hostname and/or parameterized path,
    20  // otherwise will default to returning the request `URL`'s `String()`.
    21  func GetRawURLParameterized(req *http.Request) string {
    22  	if req == nil || req.URL == nil {
    23  		return ""
    24  	}
    25  	url := req.URL
    26  
    27  	hostName := GetServiceHostName(req.Context())
    28  	path := GetParameterizedPath(req.Context())
    29  	if path == "" && hostName == "" {
    30  		return url.String()
    31  	}
    32  	if hostName == "" {
    33  		hostName = url.Host
    34  	} else {
    35  		// Using similar formatting as DD to signal this is a parameterized value
    36  		// https://docs.datadoghq.com/tracing/troubleshooting/quantization/#overview
    37  		hostName = fmt.Sprintf("{%s}", hostName)
    38  	}
    39  	if path == "" {
    40  		path = url.Path
    41  	}
    42  
    43  	// Stripped down version of "net/url" `URL.String()`
    44  	var buf strings.Builder
    45  	if url.Scheme != "" {
    46  		buf.WriteString(url.Scheme)
    47  		buf.WriteByte(':')
    48  	}
    49  	if url.Scheme != "" || hostName != "" {
    50  		if hostName != "" || path != "" {
    51  			buf.WriteString("//")
    52  		}
    53  		if hostName != "" {
    54  			buf.WriteString(hostName)
    55  		}
    56  	}
    57  	if !strings.HasPrefix(path, "/") {
    58  		buf.WriteByte('/')
    59  	}
    60  	buf.WriteString(path)
    61  	return buf.String()
    62  }