komuw / ong

ong, is a Go http toolkit.
MIT License
16 stars 4 forks source link

new id.New() #414

Closed komuw closed 4 months ago

komuw commented 4 months ago

Because of trouble that led to https://github.com/komuw/ong/commit/ed0f7fd10a85d26d953e61f21c91b4eeaf0851ce Maybe we could do;

package main

import (
    "fmt"
    "math/rand/v2"
)

const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

func Random(n int) string {
    if n < 1 {
        n = 1
    }
    if n > 100_000 {
        // the upper limit of a slice is some significant fraction of the address space of a process.
        // https://github.com/golang/go/issues/38673#issuecomment-643885108
        n = 100_000
    }

    length := len(alphabet)
    b := make([]byte, n)

    for i := range b {
        j := rand.N(length)
        b[i] = alphabet[j]
    }

    return string(b)
}

func main() {
    for range 10 {
        fmt.Println(Random(9))
    }
}