strutil.go 1.4 KB

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