github.com/xmidt-org/webpa-common@v1.11.9/device/context.go (about)

     1  package device
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  )
     7  
     8  type key int
     9  
    10  const (
    11  	idKey key = iota
    12  	metadataKey
    13  )
    14  
    15  // GetID returns the device ID from the context if any.
    16  func GetID(ctx context.Context) (id ID, ok bool) {
    17  	id, ok = ctx.Value(idKey).(ID)
    18  	return
    19  }
    20  
    21  // WithID returns a new context with the given device ID as a value.
    22  func WithID(parent context.Context, id ID) context.Context {
    23  	return context.WithValue(parent, idKey, id)
    24  }
    25  
    26  // WithIDRequest returns a new HTTP request with the given device ID in the associated Context.
    27  func WithIDRequest(id ID, original *http.Request) *http.Request {
    28  	return original.WithContext(
    29  		WithID(original.Context(), id),
    30  	)
    31  }
    32  
    33  // WithDeviceMetadata returns a new context with the given metadata as a value.
    34  func WithDeviceMetadata(parent context.Context, metadata *Metadata) context.Context {
    35  	return context.WithValue(parent, metadataKey, metadata)
    36  }
    37  
    38  // GetDeviceMetadata returns the device metadata from the context if any.
    39  func GetDeviceMetadata(ctx context.Context) (metadata *Metadata, ok bool) {
    40  	metadata, ok = ctx.Value(metadataKey).(*Metadata)
    41  	return
    42  }