github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/exp/kvutil/key_factory.go (about)

     1  package kvutil
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  	"strings"
     7  )
     8  
     9  var argPattern = regexp.MustCompile(`\{[^{]*\}`)
    10  
    11  // Key is a function which formats arguments to a string key using
    12  // predefined key format.
    13  type Key func(args ...any) string
    14  
    15  // KeyFactory builds Key functions.
    16  type KeyFactory struct {
    17  	prefix string
    18  }
    19  
    20  // SetPrefix configures the Key functions created by the factory
    21  // to add a prefix to all generated cache keys.
    22  func (kf *KeyFactory) SetPrefix(prefix string) {
    23  	kf.prefix = prefix
    24  }
    25  
    26  // NewKey creates a Key function.
    27  //
    28  // If argNames are given (eg. arg1, arg2), it replace the placeholders of
    29  // `{argN}` in format to "%v" as key arguments, else it uses a regular
    30  // expression `\{[^{]*\}` to replace all placeholders of `{arg}` in format
    31  // to "%v" as key arguments.
    32  func (kf *KeyFactory) NewKey(format string, argNames ...string) Key {
    33  	return kf.newSprintfKey(format, argNames...)
    34  }
    35  
    36  func (kf *KeyFactory) newSprintfKey(format string, argNames ...string) Key {
    37  	var tmpl string
    38  	if len(argNames) == 0 {
    39  		tmpl = argPattern.ReplaceAllString(format, "%v")
    40  	} else {
    41  		var oldnew []string
    42  		for _, arg := range argNames {
    43  			placeholder := fmt.Sprintf("{%s}", arg)
    44  			oldnew = append(oldnew, placeholder, "%v")
    45  		}
    46  		tmpl = strings.NewReplacer(oldnew...).Replace(format)
    47  	}
    48  	return func(args ...any) string {
    49  		return kf.prefix + fmt.Sprintf(tmpl, args...)
    50  	}
    51  }