This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
package generate
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
mrand "math/rand"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ID generates an ID using crypto-random, falling back to math random when that fails
|
||||
// to avoid disrupting operation because of a faulty RNG.
|
||||
func ID(prefix string, length int) string {
|
||||
var data [32]byte
|
||||
|
||||
result := strings.Builder{}
|
||||
result.Grow(length + 32)
|
||||
result.WriteString(prefix)
|
||||
|
||||
pos := 0
|
||||
for result.Len() < length {
|
||||
if pos == 0 {
|
||||
randRead(data[:])
|
||||
}
|
||||
|
||||
result.WriteString(strconv.FormatUint(binary.BigEndian.Uint64(data[pos:pos+8]), 36))
|
||||
|
||||
pos = (pos + 8) % 32
|
||||
}
|
||||
|
||||
return result.String()[:length]
|
||||
}
|
||||
|
||||
func randRead(data []byte) {
|
||||
n, err := rand.Read(data)
|
||||
if err != nil {
|
||||
mrand.Read(data[n:])
|
||||
}
|
||||
}
|
||||
|
||||
// PostID generates a post ID.
|
||||
func PostID() string {
|
||||
return ID("P", 16)
|
||||
}
|
||||
|
||||
// StoryID generates a post ID.
|
||||
func StoryID() string {
|
||||
return ID("S", 16)
|
||||
}
|
||||
|
||||
// ChapterID generates a post ID.
|
||||
func ChapterID() string {
|
||||
return ID("SC", 24)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package generate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"git.aiterp.net/rpdata/api/models"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LogID generates a log ID in the format is 2019-05-22_191341547_RedrockAgency
|
||||
func LogID(log models.Log) string {
|
||||
if len(log.ChannelName) < 1 {
|
||||
panic("ChannelName is not valid (validate input before calling this function!)")
|
||||
}
|
||||
|
||||
datetime := log.Date.UTC().Format("2006-01-02_150405")
|
||||
milliseconds := (log.Date.UnixNano() % int64(time.Second)) / 1000000
|
||||
channelName := log.ChannelName[1:]
|
||||
|
||||
return fmt.Sprintf("%s%03d_%s", datetime, milliseconds, channelName)
|
||||
}
|
||||
Reference in New Issue
Block a user