From edf9cd34cccd9cfa0444c6fa9db96428718ed160 Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Sat, 15 Apr 2017 16:38:45 -0600 Subject: [PATCH] context: RandomString action produces a random string of random length --- caddyhttp/httpserver/context.go | 35 +++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/caddyhttp/httpserver/context.go b/caddyhttp/httpserver/context.go index 3cf43965..b19ce879 100644 --- a/caddyhttp/httpserver/context.go +++ b/caddyhttp/httpserver/context.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" "io/ioutil" + "math/rand" "net" "net/http" "net/url" @@ -353,3 +354,37 @@ func (c Context) IsMITM() bool { } return false } + +// RandomString generates a random string of random length given +// length bounds. Thanks to http://stackoverflow.com/a/31832326/1048862 +// for the clever technique that is fast and maintains proper +// distributions over the dictionary. +func (c Context) RandomString(minLen, maxLen int) string { + const ( + letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + letterIdxBits = 6 // 6 bits to represent a letter index + letterIdxMask = 1<= 0; { + if remain == 0 { + cache, remain = src.Int63(), letterIdxMax + } + if idx := int(cache & letterIdxMask); idx < len(letterBytes) { + b[i] = letterBytes[idx] + i-- + } + cache >>= letterIdxBits + remain-- + } + + return string(b) +}