github.com/projectdiscovery/nuclei/v2@v2.9.15/pkg/protocols/common/replacer/replacer.go (about)

     1  package replacer
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/projectdiscovery/fasttemplate"
     7  
     8  	"github.com/projectdiscovery/nuclei/v2/pkg/protocols/common/marker"
     9  	"github.com/projectdiscovery/nuclei/v2/pkg/types"
    10  )
    11  
    12  // Replace replaces placeholders in template with values on the fly.
    13  func Replace(template string, values map[string]interface{}) string {
    14  	valuesMap := make(map[string]interface{}, len(values))
    15  	for k, v := range values {
    16  		valuesMap[k] = types.ToString(v)
    17  	}
    18  	replaced := fasttemplate.ExecuteStringStd(template, marker.ParenthesisOpen, marker.ParenthesisClose, valuesMap)
    19  	final := fasttemplate.ExecuteStringStd(replaced, marker.General, marker.General, valuesMap)
    20  	return final
    21  }
    22  
    23  // Replace replaces one placeholder in template with one value on the fly.
    24  func ReplaceOne(template string, key string, value interface{}) string {
    25  	data := replaceOneWithMarkers(template, key, value, marker.ParenthesisOpen, marker.ParenthesisClose)
    26  	return replaceOneWithMarkers(data, key, value, marker.General, marker.General)
    27  }
    28  
    29  // replaceOneWithMarkers is a helper function that perform one time replacement
    30  func replaceOneWithMarkers(template, key string, value interface{}, openMarker, closeMarker string) string {
    31  	return strings.Replace(template, openMarker+key+closeMarker, types.ToString(value), 1)
    32  }