2023-10-24 17:16:58 +00:00
|
|
|
package dcontext
|
2015-02-05 21:56:50 +00:00
|
|
|
|
|
|
|
import (
|
2017-08-11 22:31:16 +00:00
|
|
|
"context"
|
2015-02-05 21:56:50 +00:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Since looks up key, which should be a time.Time, and returns the duration
|
|
|
|
// since that time. If the key is not found, the value returned will be zero.
|
|
|
|
// This is helpful when inferring metrics related to context execution times.
|
2017-08-11 22:31:16 +00:00
|
|
|
func Since(ctx context.Context, key interface{}) time.Duration {
|
2016-03-30 09:35:22 +00:00
|
|
|
if startedAt, ok := ctx.Value(key).(time.Time); ok {
|
|
|
|
return time.Since(startedAt)
|
2015-02-05 21:56:50 +00:00
|
|
|
}
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetStringValue returns a string value from the context. The empty string
|
|
|
|
// will be returned if not found.
|
2017-08-11 22:31:16 +00:00
|
|
|
func GetStringValue(ctx context.Context, key interface{}) (value string) {
|
2016-03-30 09:35:22 +00:00
|
|
|
if valuev, ok := ctx.Value(key).(string); ok {
|
|
|
|
value = valuev
|
2015-02-05 21:56:50 +00:00
|
|
|
}
|
|
|
|
return value
|
|
|
|
}
|