-
Notifications
You must be signed in to change notification settings - Fork 1
/
rand.go
39 lines (31 loc) · 701 Bytes
/
rand.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main
import (
"crypto/rand"
"encoding/hex"
"os"
"strings"
)
type RandStrct struct {
NumberOfBytes int
FileFlagSet bool // set true to write output to file
FileName string // output filename
}
func RandomBytes(r *RandStrct) (string, error) {
byt := make([]byte, r.NumberOfBytes)
if _, err := rand.Read(byt); err != nil {
return "", err
}
output := hex.EncodeToString(byt)
result := strings.TrimSpace(output)
if r.FileFlagSet {
f, err := os.OpenFile(r.FileName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return "", err
}
if _, err := f.WriteString(result); err != nil {
return "", err
}
return result, nil
}
return result, nil
}