-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
50 lines (45 loc) · 1.24 KB
/
utils.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
package spotlib
import (
"context"
"encoding/binary"
"io"
"time"
)
func writeVarString(w io.Writer, s []byte) error {
_, err := w.Write(binary.AppendUvarint(nil, uint64(len(s))))
if err != nil {
return err
}
_, err = w.Write(s)
return err
}
func appendVarString(buf []byte, s []byte) []byte {
buf = binary.AppendUvarint(buf, uint64(len(s)))
return append(buf, s...)
}
// WithTimeout makes it easy to call a method that requires a context with a specified timeout
// without having to worry about calling the cancel() method. Go typically suggests using defer,
// however if processing after a given method is called continues, there is a risk the cancel
// method will be called much later.
//
// This method on the other hand performs the defer of cancel, which means that cancel will be
// called properly even in case of a panic.
//
// Usage:
//
// spotlib.WithTimeout(nil, 30*time.Second, func(ctx context.Context) {
// res, err = c.methodWithCtx(ctx)
// }
//
// if err := nil { ...
func WithTimeout(ctx context.Context, timeout time.Duration, cb func(context.Context)) {
if ctx == nil {
ctx = context.Background()
}
if timeout > 0 {
var cancel func()
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
cb(ctx)
}