-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add template helper library (#10500)
- Loading branch information
Showing
6 changed files
with
790 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
package template | ||
|
||
import ( | ||
"crypto/sha256" | ||
"fmt" | ||
"strconv" | ||
"strings" | ||
"time" | ||
|
||
UUID "github.com/hashicorp/go-uuid" | ||
) | ||
|
||
func nowSeconds() string { | ||
return strconv.FormatInt(time.Now().Unix(), 10) | ||
} | ||
|
||
func nowNano() string { | ||
return strconv.FormatInt(time.Now().UnixNano(), 10) | ||
} | ||
|
||
func truncate(maxLen int, str string) (string, error) { | ||
if maxLen <= 0 { | ||
return "", fmt.Errorf("max length must be > 0 but was %d", maxLen) | ||
} | ||
if len(str) > maxLen { | ||
return str[:maxLen], nil | ||
} | ||
return str, nil | ||
} | ||
|
||
const ( | ||
sha256HashLen = 8 | ||
) | ||
|
||
func truncateSHA256(maxLen int, str string) (string, error) { | ||
if maxLen <= 8 { | ||
return "", fmt.Errorf("max length must be > 8 but was %d", maxLen) | ||
} | ||
|
||
if len(str) <= maxLen { | ||
return str, nil | ||
} | ||
|
||
truncIndex := maxLen - sha256HashLen | ||
hash := hashSHA256(str[truncIndex:]) | ||
result := fmt.Sprintf("%s%s", str[:truncIndex], hash[:sha256HashLen]) | ||
return result, nil | ||
} | ||
|
||
func hashSHA256(str string) string { | ||
return fmt.Sprintf("%x", sha256.Sum256([]byte(str))) | ||
} | ||
|
||
func uppercase(str string) string { | ||
return strings.ToUpper(str) | ||
} | ||
|
||
func lowercase(str string) string { | ||
return strings.ToLower(str) | ||
} | ||
|
||
func replace(find string, replace string, str string) string { | ||
return strings.ReplaceAll(str, find, replace) | ||
} | ||
|
||
func uuid() (string, error) { | ||
return UUID.GenerateUUID() | ||
} |
Oops, something went wrong.