54 lines
819 B
Go
54 lines
819 B
Go
package util
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"time"
|
|
)
|
|
|
|
const RedrawInterval = 250 * time.Millisecond
|
|
|
|
func Periodic(ctx context.Context, interval time.Duration, fn func() error) {
|
|
if err := fn(); err != nil {
|
|
panic(err)
|
|
}
|
|
ticker := time.NewTicker(interval)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ticker.C:
|
|
if err := fn(); err != nil {
|
|
panic(err)
|
|
}
|
|
case <-ctx.Done():
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func PanicOnErrorWithResult[E any](result E, err error) E {
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return result
|
|
}
|
|
|
|
func PanicOnError(err error) {
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
func DecodeJSON(r io.Reader, v any) error {
|
|
dec := json.NewDecoder(r)
|
|
if err := dec.Decode(v); err != nil {
|
|
if err == io.EOF {
|
|
return fmt.Errorf("empty stats stream")
|
|
}
|
|
return err
|
|
}
|
|
return nil
|
|
}
|