Metadata

Microservices interact through HTTP and gRPC API, so the service architecture needs to be used for uniform Metadata transport. Currently, you could also carry a Metadata pass in gRPC, The metadata will be put into HTTP Header, and then upstream will receive the corresponding Metadata Information. So it’s also designed to be delivered via HTTP Header, first wrapped in a key/value structure in a framework through a metadata package, and then carried to Transport Header.

Default Metadata Convention

  • x-md-global-xxx,will be transported globally, e.g. mirror/color/criticality
  • x-md-local-xxx,will be transported locally, e.g. caller

You could also set your custom key prefix in middleware/metadata for constant metadata.

Usage

First, the middleware/metadata plug-in should be configured to client/server, and then you can customize the transport key prefix, or the metadata constant, such as caller. Finally, it can be configured or obtained through NewClientContext or FromServerContext in the metadata package.

Configuration

  1. // https://github.com/go-kratos/examples/tree/main/metadata
  2. // Register the metadata middleware to gRPC or HTTP's server or client
  3. // server
  4. grpcSrv := grpc.NewServer(
  5. grpc.Address(":9000"),
  6. grpc.Middleware(
  7. metadata.Server(),
  8. ),
  9. )
  10. httpSrv := http.NewServer(
  11. http.Address(":8000"),
  12. http.Middleware(
  13. metadata.Server(),
  14. ),
  15. )
  16. // client
  17. conn, err := grpc.DialInsecure(
  18. context.Background(),
  19. grpc.WithEndpoint("127.0.0.1:9000"),
  20. grpc.WithMiddleware(
  21. metadata.Client(),
  22. ),
  23. )

Get metadata value

  1. if md, ok := metadata.FromServerContext(ctx); ok {
  2. extra = md.Get("x-md-global-extra")
  3. }

Set metadata

  1. ctx = metadata.AppendToClientContext(ctx, "x-md-global-extra", "2233")