strutil.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package strutil
  2. import (
  3. "crypto/rand"
  4. "math/big"
  5. "strings"
  6. "unicode"
  7. )
  8. // ToUpperFirst returns s with only the first Unicode letter mapped to its upper case.
  9. func ToUpperFirst(s string) string {
  10. for i, v := range s {
  11. return string(unicode.ToUpper(v)) + s[i+1:]
  12. }
  13. return ""
  14. }
  15. // RandomChars returns a generated string in given number of random characters.
  16. func RandomChars(n int) (string, error) {
  17. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  18. randomInt := func(max *big.Int) (int, error) {
  19. r, err := rand.Int(rand.Reader, max)
  20. if err != nil {
  21. return 0, err
  22. }
  23. return int(r.Int64()), nil
  24. }
  25. buffer := make([]byte, n)
  26. max := big.NewInt(int64(len(alphanum)))
  27. for i := range n {
  28. index, err := randomInt(max)
  29. if err != nil {
  30. return "", err
  31. }
  32. buffer[i] = alphanum[index]
  33. }
  34. return string(buffer), nil
  35. }
  36. // Ellipsis returns a truncated string and appends "..." to the end of the
  37. // string if the string length is larger than the threshold. Otherwise, the
  38. // original string is returned.
  39. func Ellipsis(str string, threshold int) string {
  40. if len(str) <= threshold || threshold < 0 {
  41. return str
  42. }
  43. return str[:threshold] + "..."
  44. }
  45. // Truncate returns a truncated string if its length is over the limit.
  46. // Otherwise, it returns the original string.
  47. func Truncate(str string, limit int) string {
  48. if len(str) < limit {
  49. return str
  50. }
  51. return str[:limit]
  52. }
  53. // ContainsFold reports whether s is within the slice, ignoring case.
  54. func ContainsFold(ss []string, s string) bool {
  55. for _, v := range ss {
  56. if strings.EqualFold(v, s) {
  57. return true
  58. }
  59. }
  60. return false
  61. }