This commit is contained in:
2026-07-04 01:53:00 +01:00
parent e2fe6c9e19
commit 0550aec6ad
2 changed files with 55 additions and 5 deletions
+2 -2
View File
@@ -10,13 +10,13 @@ package main
import (
"fmt"
"github.com/annybs/go/random"
"code.aneur.in/go/random"
)
func main() {
n := make([]bool, 10)
for i := range n {
fmt.Println(random.Str(4 + i))
fmt.Println(random.Alpha(4 + i))
}
}
```
+53 -3
View File
@@ -1,9 +1,56 @@
package random
import "math/rand"
import (
"math/rand"
"strings"
)
// Str generates a random string of the specified length using an alphanumeric character set.
var Str = String([]rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"))
// Standard character set.
const (
CharsetAlpha string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
CharsetAlphanumeric string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
CharsetAlphaLower string = "abcdefghijklmnopqrstuvwxyz"
CharsetAlphaUpper string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
CharsetNumeric string = "0123456789"
CharsetSymbols string = "!@#$%^&*()-=_+[]{};:,.<>/?"
)
// Alpha generates a random string of the specified length using a mixed-case alphabetical character set.
var Alpha = String([]rune(CharsetAlpha))
// Alphanumeric generates a random string of the specified length using an alphanumeric character set.
var Alphanumeric = String([]rune(CharsetAlphanumeric))
// AlphaLower generates a random string of the specified length using a lowercase alphabetical character set.
var AlphaLower = String([]rune(CharsetAlphaLower))
// AlphaUpper generates a random string of the specified length using an uppercase alphabetical character set.
var AlphaUpper = String([]rune(CharsetAlphaUpper))
// Numeric generates a random string of the specified length containing numbers only.
var Numeric = String([]rune(CharsetNumeric))
// Password generates a random string of the specified length, including the specified counts of numbers and symbols.
func Password(length, numbers, symbols int) string {
parts := []string{
Alpha(length - numbers - symbols),
Numeric(numbers),
Symbols(symbols),
}
str := strings.Join(parts, "")
m := map[int]rune{}
for i, c := range str {
m[i] = c
}
jumbled := []rune{}
for _, c := range m {
jumbled = append(jumbled, c)
}
return string(jumbled)
}
// String returns a function that can be used to generate a random string of the specified length using the given character set.
func String(chars []rune) func(length int) string {
@@ -16,3 +63,6 @@ func String(chars []rune) func(length int) string {
return string(s)
}
}
// Symbols generates a random string of the specified length using a limited selection of symbols.
var Symbols = String([]rune(CharsetSymbols))