Skip to content

Commit

Permalink
Merge pull request #10 from spotlibs/feat/metadata-with-context
Browse files Browse the repository at this point in the history
feat: metadata with context
  • Loading branch information
mdanialr authored Sep 9, 2024
2 parents 14e0065 + c22cde3 commit 20a1c13
Showing 1 changed file with 33 additions and 5 deletions.
38 changes: 33 additions & 5 deletions ctx/metadata.go
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -70,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
}

0 comments on commit 20a1c13

Please sign in to comment.