-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil.go
70 lines (60 loc) · 1.54 KB
/
util.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package letsrest
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
)
// GenerateRandomBytes returns securely generated random bytes.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
// case the caller should not continue.
func GenerateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
// Note that err == nil only if we read len(b) bytes.
if err != nil {
return nil, err
}
return b, nil
}
// GenerateRandomString returns a URL-safe, base64 encoded
// securely generated random string.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
// case the caller should not continue.
func GenerateRandomString(s int) (string, error) {
b, err := GenerateRandomBytes(s)
return base64.URLEncoding.EncodeToString(b), err
}
func Must(err error, msg ...interface{}) {
if err != nil {
log.Fatal(err, msg)
}
}
func PrintJSON(i interface{}) {
fmt.Println("JSON: ", GetJSON(i))
}
func GetJSON(i interface{}) string {
j, err := json.Marshal(i)
Must(err, "Ma")
return string(j)
}
type LimitedErrReader struct {
R io.Reader // underlying reader
N int64 // max bytes remaining
}
var bodySizeLimitExceededErr = errors.New("error.body.size.limit.exceeded")
func (l *LimitedErrReader) Read(p []byte) (n int, err error) {
if l.N <= 0 {
return 0, bodySizeLimitExceededErr
}
if int64(len(p)) > l.N {
p = p[0:l.N]
}
n, err = l.R.Read(p)
l.N -= int64(n)
return
}