github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/stub/utils.go (about)

     1  package stub
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  	"strings"
     7  )
     8  
     9  // fillParams traverse the `pathPattern` and detect params with format `:name` and
    10  // replace them using the function `f` provides in arguments.
    11  func fillParams(pathPattern string, f func(key string) string) string {
    12  	pathPattern = convertLegacyPathFormat(pathPattern)
    13  
    14  	out := strings.Builder{}
    15  	param := strings.Builder{}
    16  	readingMode := false
    17  
    18  	for _, r := range pathPattern {
    19  		if readingMode {
    20  			if r != '}' {
    21  				param.WriteRune(r)
    22  
    23  				continue
    24  			}
    25  			v := f(param.String())
    26  			if v != "" {
    27  				out.WriteString(v)
    28  			} else {
    29  				out.WriteString("_")
    30  			}
    31  			param.Reset()
    32  			readingMode = false
    33  		}
    34  		if !readingMode && r == '{' {
    35  			readingMode = true
    36  
    37  			continue
    38  		}
    39  
    40  		if r != '}' {
    41  			out.WriteRune(r)
    42  		}
    43  	}
    44  
    45  	if param.Len() > 0 {
    46  		v := f(param.String())
    47  		if v != "" {
    48  			out.WriteString(v)
    49  		} else {
    50  			out.WriteString("_")
    51  		}
    52  	}
    53  
    54  	return out.String()
    55  }
    56  
    57  var legacyPathFormatRegEx = regexp.MustCompile(`/:([-_a-zA-Z0-9]*)[^/]`)
    58  
    59  func convertLegacyPathFormat(path string) string {
    60  	return legacyPathFormatRegEx.ReplaceAllStringFunc(
    61  		path,
    62  		func(s string) string {
    63  			return fmt.Sprintf("/{%s}", strings.TrimPrefix(s, "/:"))
    64  		},
    65  	)
    66  }