Metadata

Microservices interact with each other via HTTP and gRPC API, so the service architecture should use unified Metadata transmission.
At present, It is possible for gRPC to carry Metadata, by putting Metadata in HTTP Header, so the upstream can receive the corresponding Metadata information. Therefore, in Kratos, it is also carried by HTTP Header. In the framework, it is packaged in key/value structure, and carried in 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

It is also possible to customize the key prefix in middleware/metadata for constant metadata.

Usage

First, you need to configure corresponding middleware/metadata plug-ins for the client/server. Then you can customize the key prefix or metadata constant, e.g. caller. Finally you can use NewClientContext or FromServerContext from Metadata package to configure or get the metadata.

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")