fix: create RandomGenerator interface and struct for testing purpose #181
Some checks failed
Build Docker Image / Explore-Gitea-Actions (push) Has been cancelled
Some checks failed
Build Docker Image / Explore-Gitea-Actions (push) Has been cancelled
This commit is contained in:
48
service/random_generator.go
Normal file
48
service/random_generator.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"me-fit/types"
|
||||
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"log/slog"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type RandomGenerator interface {
|
||||
Bytes(size int) ([]byte, error)
|
||||
String(size int) (string, error)
|
||||
UUID() (uuid.UUID, error)
|
||||
}
|
||||
|
||||
type RandomGeneratorImpl struct {
|
||||
}
|
||||
|
||||
func NewRandomGeneratorImpl() *RandomGeneratorImpl {
|
||||
return &RandomGeneratorImpl{}
|
||||
}
|
||||
|
||||
func (r *RandomGeneratorImpl) Bytes(size int) ([]byte, error) {
|
||||
b := make([]byte, 32)
|
||||
_, err := rand.Read(b)
|
||||
if err != nil {
|
||||
slog.Error("Error generating random bytes: " + err.Error())
|
||||
return []byte{}, types.ErrInternal
|
||||
}
|
||||
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (r *RandomGeneratorImpl) String(size int) (string, error) {
|
||||
bytes, err := r.Bytes(size)
|
||||
if err != nil {
|
||||
return "", types.ErrInternal
|
||||
}
|
||||
|
||||
return base64.StdEncoding.EncodeToString(bytes), nil
|
||||
}
|
||||
|
||||
func (r *RandomGeneratorImpl) UUID() (uuid.UUID, error) {
|
||||
return uuid.NewRandom()
|
||||
}
|
||||
Reference in New Issue
Block a user