aboutsummaryrefslogtreecommitdiff
path: root/internal/util/util.go
blob: f8f12baeff1576d9c81f53a4b9c17856f8ba641f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package util

import (
  "math/rand" // not crypto secure
  "regexp"
  "strings"
)

const randHostnameCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"
const randStringCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

var (
  // Up to 15 characters; only letters, digits, and hyphens (with hyphens not at the start or end).
  randHostnameRegex = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9-]{0,14}[a-zA-Z0-9]$`)
)

func RandomHostname() (hostname string) {
  for {
    // between 2 and 10 characters
    if hostname = RandomStringFromCharset(randHostnameCharset, rand.Intn(8)+2); randHostnameRegex.MatchString(hostname) {
      return
    }
  }
}

func RandomString() string {
  return RandomStringFromCharset(randStringCharset, rand.Intn(10)+6)
}

func RandomStringFromCharset(charset string, length int) string {
  b := make([]byte, length)
  for i := range length {
    b[i] = charset[rand.Intn(len(charset))]
  }
  return string(b)
}

func RandomStringIfBlank(s string) string {
  if s == "" {
    return RandomString()
  }
  return s
}

func CheckNullString(s string) string {
  if !strings.HasSuffix(s, "\x00") {
    return s + "\x00"
  }
  return s
}