util.go 789 B

1234567891011121314151617181920212223242526272829303132
  1. package context
  2. import (
  3. "time"
  4. )
  5. // Since looks up key, which should be a time.Time, and returns the duration
  6. // since that time. If the key is not found, the value returned will be zero.
  7. // This is helpful when inferring metrics related to context execution times.
  8. func Since(ctx Context, key interface{}) time.Duration {
  9. startedAtI := ctx.Value(key)
  10. if startedAtI != nil {
  11. if startedAt, ok := startedAtI.(time.Time); ok {
  12. return time.Since(startedAt)
  13. }
  14. }
  15. return 0
  16. }
  17. // GetStringValue returns a string value from the context. The empty string
  18. // will be returned if not found.
  19. func GetStringValue(ctx Context, key string) (value string) {
  20. stringi := ctx.Value(key)
  21. if stringi != nil {
  22. if valuev, ok := stringi.(string); ok {
  23. value = valuev
  24. }
  25. }
  26. return value
  27. }