From dd8f34813100aefc91f6d86431d303ccf355e4dc Mon Sep 17 00:00:00 2001 From: Danial Date: Mon, 9 Sep 2024 14:31:43 +0700 Subject: [PATCH 1/2] feat: handle metadata with context --- ctx/metadata.go | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/ctx/metadata.go b/ctx/metadata.go index 1232928..7e0e49b 100644 --- a/ctx/metadata.go +++ b/ctx/metadata.go @@ -1,6 +1,15 @@ package ctx -import "github.com/goravel/framework/contracts/http" +import ( + "context" + + "github.com/goravel/framework/contracts/http" +) + +// keyMetadata custom type that can prevent collision. +type keyMetadata int + +const keyMetadataCtx keyMetadata = iota // metadataKey key to identify that a value in context is set and get from this // package. @@ -31,6 +40,25 @@ type Metadata struct { ApiKey string } +// Set inject given Metadata to context with custom key to make sure that the +// value is correct. +func Set(ctx context.Context, mt Metadata) context.Context { + return context.WithValue(ctx, keyMetadataCtx, mt) +} + +// Get retrieve Metadata from given context with key from this pkg. +func Get(ctx context.Context) Metadata { + if mt, ok := ctx.Value(keyMetadataCtx).(Metadata); ok { + return mt + } + return Metadata{} +} + +// PassToContext pass Metadata from http.Context to context. +func PassToContext(c http.Context) context.Context { + return Set(c, ParseRequest(c)) +} + // ParseRequest return Metadata from given http context but return empty data // instead if no data were found. func ParseRequest(c http.Context) Metadata { From c22cde3b8182cbcdff59e23e124fe02eb900539e Mon Sep 17 00:00:00 2001 From: Danial Date: Mon, 9 Sep 2024 14:31:48 +0700 Subject: [PATCH 2/2] ref: get request id with context instead of http.Context --- ctx/metadata.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ctx/metadata.go b/ctx/metadata.go index 7e0e49b..873fe39 100644 --- a/ctx/metadata.go +++ b/ctx/metadata.go @@ -98,8 +98,8 @@ func SetFromRequestHeader(c http.Context) { c.WithValue(metadataKey, mt) } -// GetReqId shortcut of ParseRequest with ReqId to get request id from given -// http context. -func GetReqId(c http.Context) string { - return ParseRequest(c).ReqId +// GetReqId extract request id from given context. This is a shortcut for Get +// with ReqId to get the request id from given context. +func GetReqId(c context.Context) string { + return Get(c).ReqId }