context.go 657 B

12345678910111213141516171819202122232425262728293031323334
  1. package context
  2. import (
  3. "context"
  4. "fmt"
  5. "google.golang.org/grpc/metadata"
  6. )
  7. func AppendToContext(ctx context.Context, key string, value interface{}) context.Context {
  8. ctx = context.WithValue(ctx, key, value)
  9. _value := ""
  10. switch value.(type) {
  11. case []byte:
  12. _value = string(value.([]byte))
  13. break
  14. case string:
  15. _value = value.(string)
  16. break
  17. default:
  18. _value = fmt.Sprint(value)
  19. break
  20. }
  21. md, ok := metadata.FromOutgoingContext(ctx)
  22. if !ok {
  23. md = make(map[string][]string)
  24. md.Set(key, _value)
  25. ctx = metadata.NewOutgoingContext(ctx, md)
  26. return ctx
  27. }
  28. md.Set(key, _value)
  29. ctx = metadata.NewOutgoingContext(ctx, md)
  30. return ctx
  31. }