Files
spend-sparrow/service/random_generator.go

50 lines
907 B
Go

package service
import (
"web-app-template/log"
"web-app-template/types"
"crypto/rand"
"encoding/base64"
"github.com/google/uuid"
)
type Random interface {
Bytes(size int) ([]byte, error)
String(size int) (string, error)
UUID() (uuid.UUID, error)
}
type RandomImpl struct {
}
func NewRandomImpl() *RandomImpl {
return &RandomImpl{}
}
func (r *RandomImpl) Bytes(size int) ([]byte, error) {
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
log.Error("Error generating random bytes: %v", err)
return []byte{}, types.ErrInternal
}
return b, nil
}
func (r *RandomImpl) String(size int) (string, error) {
bytes, err := r.Bytes(size)
if err != nil {
log.Error("Error generating random string: %v", err)
return "", types.ErrInternal
}
return base64.StdEncoding.EncodeToString(bytes), nil
}
func (r *RandomImpl) UUID() (uuid.UUID, error) {
return uuid.NewRandom()
}