github.com/blend/go-sdk@v1.20220411.3/statsd/tag.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package statsd 9 10 import ( 11 "strings" 12 "unicode" 13 ) 14 15 // Tag formats a tag with a given key and value. 16 // For tags in the form `key` use an empty string for the value. 17 func Tag(key, value string) string { 18 key = cleanTagElement(key) 19 value = cleanTagElement(value) 20 return key + ":" + value 21 } 22 23 // SplitTag splits a given tag in a key and a value 24 func SplitTag(tag string) (key, value string) { 25 parts := strings.SplitN(tag, ":", 2) 26 if len(parts) > 0 { 27 key = parts[0] 28 } 29 if len(parts) > 1 { 30 value = parts[1] 31 } 32 return 33 } 34 35 // cleansTagElement cleans up tag elements as best as it can 36 // per the spec at https://docs.datadoghq.com/tagging/ 37 func cleanTagElement(value string) string { 38 valueRunes := []rune(value) 39 var r rune 40 for x := 0; x < len(valueRunes); x++ { 41 r = valueRunes[x] 42 // letters 43 if unicode.IsLetter(r) { 44 continue 45 } 46 // digits 47 if unicode.IsDigit(r) { 48 continue 49 } 50 // allowed symbols 51 switch r { 52 case '-', ':', '_', '.', '/', '\\': 53 continue 54 default: 55 } 56 // everything else 57 valueRunes[x] = '_' 58 continue 59 } 60 return string(valueRunes) 61 }