Files
micro-server-http/metadata.go
pugnack 545e372b82
Some checks failed
coverage / build (push) Has been skipped
test / test (push) Successful in 3m20s
sync / sync (push) Has been cancelled
breaking change: modify API for working with response metadata (#213)
* implement functions to append/get metadata and set/get status code

* сhanged behavior to return nil instead of empty metadata for getResponseMetadata()

* сhanged work with HTTP headers to use direct array assignment instead of for-range

* fix linters

* fix meter handler

* fix uninitialized response metadata for incoming context

* removed a useless test

* metrics handler has been fixed to work with compressed data
2025-05-03 12:09:52 +03:00

48 lines
1.3 KiB
Go

package http
import (
"context"
"go.unistack.org/micro/v4/metadata"
)
type (
rspMetadataKey struct{}
rspMetadataVal struct {
m metadata.Metadata
}
)
// AppendResponseMetadata adds metadata entries to metadata.Metadata stored in the context.
// It expects the context to contain a *rspMetadataVal value under the rspMetadataKey{} key.
// If the value is missing or invalid, the function does nothing.
//
// Note: this function is not thread-safe. Synchronization is required if used from multiple goroutines.
func AppendResponseMetadata(ctx context.Context, md metadata.Metadata) {
if md == nil {
return
}
val, ok := ctx.Value(rspMetadataKey{}).(*rspMetadataVal)
if !ok || val == nil || val.m == nil {
return
}
for key, values := range md {
val.m.Append(key, values...)
}
}
// getResponseMetadata retrieves the metadata.Metadata stored in the context.
//
// Note: this function is not thread-safe. Synchronization is required if used from multiple goroutines.
// If you plan to modify the returned metadata, make a full copy to avoid affecting shared state.
func getResponseMetadata(ctx context.Context) metadata.Metadata {
val, ok := ctx.Value(rspMetadataKey{}).(*rspMetadataVal)
if !ok || val == nil || val.m == nil {
return nil
}
return val.m
}