|
1 | 1 | package middleware
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "bufio" |
4 | 5 | "crypto/rand"
|
5 |
| - "fmt" |
| 6 | + "io" |
6 | 7 | "strings"
|
| 8 | + "sync" |
7 | 9 | )
|
8 | 10 |
|
9 | 11 | func matchScheme(domain, pattern string) bool {
|
@@ -55,17 +57,38 @@ func matchSubdomain(domain, pattern string) bool {
|
55 | 57 | return false
|
56 | 58 | }
|
57 | 59 |
|
| 60 | +// https://tip.golang.org/doc/go1.19#:~:text=Read%20no%20longer%20buffers%20random%20data%20obtained%20from%20the%20operating%20system%20between%20calls |
| 61 | +var randomReaderPool = sync.Pool{New: func() interface{} { |
| 62 | + return bufio.NewReader(rand.Reader) |
| 63 | +}} |
| 64 | + |
| 65 | +const randomStringCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" |
| 66 | +const randomStringCharsetLen = 52 // len(randomStringCharset) |
| 67 | +const randomStringMaxByte = 255 - (256 % randomStringCharsetLen) |
| 68 | + |
58 | 69 | func randomString(length uint8) string {
|
59 |
| - charset := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" |
| 70 | + reader := randomReaderPool.Get().(*bufio.Reader) |
| 71 | + defer randomReaderPool.Put(reader) |
60 | 72 |
|
61 |
| - bytes := make([]byte, length) |
62 |
| - _, err := rand.Read(bytes) |
63 |
| - if err != nil { |
64 |
| - // we are out of random. let the request fail |
65 |
| - panic(fmt.Errorf("echo randomString failed to read random bytes: %w", err)) |
66 |
| - } |
67 |
| - for i, b := range bytes { |
68 |
| - bytes[i] = charset[b%byte(len(charset))] |
| 73 | + b := make([]byte, length) |
| 74 | + r := make([]byte, length+(length/4)) // perf: avoid read from rand.Reader many times |
| 75 | + var i uint8 = 0 |
| 76 | + |
| 77 | + for { |
| 78 | + _, err := io.ReadFull(reader, r) |
| 79 | + if err != nil { |
| 80 | + panic("unexpected error happened when reading from bufio.NewReader(crypto/rand.Reader)") |
| 81 | + } |
| 82 | + for _, rb := range r { |
| 83 | + if rb > randomStringMaxByte { |
| 84 | + // Skip this number to avoid bias. |
| 85 | + continue |
| 86 | + } |
| 87 | + b[i] = randomStringCharset[rb%randomStringCharsetLen] |
| 88 | + i++ |
| 89 | + if i == length { |
| 90 | + return string(b) |
| 91 | + } |
| 92 | + } |
69 | 93 | }
|
70 |
| - return string(bytes) |
71 | 94 | }
|
0 commit comments