string.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package stringext
  2. import (
  3. "encoding/base64"
  4. "strings"
  5. "golang.org/x/text/cases"
  6. "golang.org/x/text/language"
  7. )
  8. func Capitalize(text string) string {
  9. return cases.Title(language.English, cases.Compact).String(text)
  10. }
  11. // NormalizeSpace normalizes whitespace in the given content string.
  12. // It replaces Windows-style line endings with Unix-style line endings,
  13. // converts tabs to four spaces, and trims leading and trailing whitespace.
  14. func NormalizeSpace(content string) string {
  15. content = strings.ReplaceAll(content, "\r\n", "\n")
  16. content = strings.ReplaceAll(content, "\t", " ")
  17. content = strings.TrimSpace(content)
  18. return content
  19. }
  20. // IsValidBase64 reports whether s is canonical base64 under standard
  21. // encoding (RFC 4648). It requires that s round-trips through
  22. // decode/encode unchanged — rejecting whitespace, missing padding,
  23. // and other leniencies that DecodeString alone would accept.
  24. func IsValidBase64(s string) bool {
  25. if s == "" {
  26. return false
  27. }
  28. decoded, err := base64.StdEncoding.DecodeString(s)
  29. if err != nil {
  30. return false
  31. }
  32. // Round-trip check rejects whitespace, missing padding, and other
  33. // leniencies that DecodeString silently accepts.
  34. return base64.StdEncoding.EncodeToString(decoded) == s
  35. }