github.com/LazyboyChen7/engine@v17.12.1-ce-rc2+incompatible/daemon/logger/templates/templates.go (about)

     1  package templates
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"strings"
     7  	"text/template"
     8  )
     9  
    10  // basicFunctions are the set of initial
    11  // functions provided to every template.
    12  var basicFunctions = template.FuncMap{
    13  	"json": func(v interface{}) string {
    14  		buf := &bytes.Buffer{}
    15  		enc := json.NewEncoder(buf)
    16  		enc.SetEscapeHTML(false)
    17  		enc.Encode(v)
    18  		// Remove the trailing new line added by the encoder
    19  		return strings.TrimSpace(buf.String())
    20  	},
    21  	"split":    strings.Split,
    22  	"join":     strings.Join,
    23  	"title":    strings.Title,
    24  	"lower":    strings.ToLower,
    25  	"upper":    strings.ToUpper,
    26  	"pad":      padWithSpace,
    27  	"truncate": truncateWithLength,
    28  }
    29  
    30  // NewParse creates a new tagged template with the basic functions
    31  // and parses the given format.
    32  func NewParse(tag, format string) (*template.Template, error) {
    33  	return template.New(tag).Funcs(basicFunctions).Parse(format)
    34  }
    35  
    36  // padWithSpace adds whitespace to the input if the input is non-empty
    37  func padWithSpace(source string, prefix, suffix int) string {
    38  	if source == "" {
    39  		return source
    40  	}
    41  	return strings.Repeat(" ", prefix) + source + strings.Repeat(" ", suffix)
    42  }
    43  
    44  // truncateWithLength truncates the source string up to the length provided by the input
    45  func truncateWithLength(source string, length int) string {
    46  	if len(source) < length {
    47  		return source
    48  	}
    49  	return source[:length]
    50  }