Documentation ¶
Overview ¶
Package expvarx provides some extensions to the expvar package.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type SafeFunc ¶
type SafeFunc struct {
// contains filtered or unexported fields
}
SafeFunc is a wrapper around expvar.Func that guards against unbounded call time and ensures that only a single call is in progress at any given time.
func NewSafeFunc ¶
NewSafeFunc returns a new SafeFunc that wraps f. If f takes longer than limit to execute then Value calls return nil. If onSlow is non-nil, it is called when f takes longer than limit to execute. onSlow is called with the duration of the slow call and the final computed value.
Example ¶
// An artificial blocker to emulate a slow operation. blocker := make(chan struct{}) // limit is the amount of time a call can take before Value returns nil. No // new calls to the unsafe func will be started until the slow call // completes, at which point onSlow will be called. limit := time.Millisecond // onSlow is called with the final call duration and the final value in the // event a slow call. onSlow := func(d time.Duration, v any) { _ = d // d contains the time the call took _ = v // v contains the final value computed by the slow call fmt.Println("slow call!") } // An unsafe expvar.Func that blocks on the blocker channel. unsafeFunc := expvar.Func(func() any { for range blocker { } return "hello world" }) // f implements the same interface as expvar.Func, but returns nil values // when the unsafe func is too slow. f := NewSafeFunc(unsafeFunc, limit, onSlow) fmt.Println(f.Value()) fmt.Println(f.Value()) close(blocker) time.Sleep(time.Millisecond) fmt.Println(f.Value())
Output: <nil> <nil> slow call! hello world
func (*SafeFunc) String ¶
String implements stringer in the same pattern as expvar.Func, calling Value and serializing the result as JSON, ignoring errors.
func (*SafeFunc) Value ¶
Value acts similarly to expvar.Func.Value, but if the underlying function takes longer than the configured limit, all callers will receive nil until the underlying operation completes. On completion of the underlying operation, the onSlow callback is called if set.