github.com/blend/go-sdk@v1.20220411.3/web/context.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package web
     9  
    10  import (
    11  	"context"
    12  	"time"
    13  )
    14  
    15  type appKey struct{}
    16  
    17  // WithApp adds an app to a context.
    18  func WithApp(ctx context.Context, app *App) context.Context {
    19  	return context.WithValue(ctx, appKey{}, app)
    20  }
    21  
    22  // GetApp gets an app off a context.
    23  func GetApp(ctx context.Context) *App {
    24  	if value := ctx.Value(appKey{}); value != nil {
    25  		if typed, ok := value.(*App); ok {
    26  			return typed
    27  		}
    28  	}
    29  	return nil
    30  }
    31  
    32  type requestStartedKey struct{}
    33  
    34  // WithRequestStarted sets the request started time on a context.
    35  func WithRequestStarted(ctx context.Context, requestStarted time.Time) context.Context {
    36  	return context.WithValue(ctx, requestStartedKey{}, requestStarted)
    37  }
    38  
    39  // GetRequestStarted gets the request started time from a context.
    40  func GetRequestStarted(ctx context.Context) time.Time {
    41  	if value := ctx.Value(requestStartedKey{}); value != nil {
    42  		if typed, ok := value.(time.Time); ok {
    43  			return typed
    44  		}
    45  	}
    46  	return time.Time{}
    47  }
    48  
    49  type sessionKey struct{}
    50  
    51  // WithSession sets a session on a context.
    52  func WithSession(ctx context.Context, session *Session) context.Context {
    53  	return context.WithValue(ctx, sessionKey{}, session)
    54  }
    55  
    56  // GetSession gets a session off a context.
    57  func GetSession(ctx context.Context) *Session {
    58  	if value := ctx.Value(sessionKey{}); value != nil {
    59  		if typed, ok := value.(*Session); ok {
    60  			return typed
    61  		}
    62  	}
    63  	return nil
    64  }