sanitize.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Copyright 2017, OpenCensus Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package internal
  15. import (
  16. "strings"
  17. "unicode"
  18. )
  19. const labelKeySizeLimit = 100
  20. // Sanitize returns a string that is trunacated to 100 characters if it's too
  21. // long, and replaces non-alphanumeric characters to underscores.
  22. func Sanitize(s string) string {
  23. if len(s) == 0 {
  24. return s
  25. }
  26. if len(s) > labelKeySizeLimit {
  27. s = s[:labelKeySizeLimit]
  28. }
  29. s = strings.Map(sanitizeRune, s)
  30. if unicode.IsDigit(rune(s[0])) {
  31. s = "key_" + s
  32. }
  33. if s[0] == '_' {
  34. s = "key" + s
  35. }
  36. return s
  37. }
  38. // converts anything that is not a letter or digit to an underscore
  39. func sanitizeRune(r rune) rune {
  40. if unicode.IsLetter(r) || unicode.IsDigit(r) {
  41. return r
  42. }
  43. // Everything else turns into an underscore
  44. return '_'
  45. }