github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xctx/context.go (about)

     1  package xctx
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  )
     7  
     8  // ReadInt try read int stored in context.Context identified by key.
     9  func ReadInt(ctx context.Context, key interface{}) (int, bool) {
    10  	v := ctx.Value(key)
    11  	if v == nil {
    12  		return 0, false
    13  	}
    14  	switch i := v.(type) {
    15  	case int:
    16  		return i, true
    17  	case int64:
    18  		return int(i), true
    19  	case int32:
    20  		return int(i), true
    21  	default:
    22  		return 0, false
    23  	}
    24  }
    25  
    26  // ReadInt64 try read int64 stored in context.Context identified by key.
    27  func ReadInt64(ctx context.Context, key interface{}) (int64, bool) {
    28  	v := ctx.Value(key)
    29  	if v == nil {
    30  		return 0, false
    31  	}
    32  	switch i := v.(type) {
    33  	case int:
    34  		return int64(i), true
    35  	case int64:
    36  		return i, true
    37  	case int32:
    38  		return int64(i), true
    39  	default:
    40  		return 0, false
    41  	}
    42  }
    43  
    44  // ReadString try read string stored in context.Context identified by key.
    45  func ReadString(ctx context.Context, key interface{}) (string, bool) {
    46  	v := ctx.Value(key)
    47  	if v == nil {
    48  		return "", false
    49  	}
    50  	switch i := v.(type) {
    51  	case string:
    52  		return i, true
    53  	case []byte:
    54  		return string(i), true
    55  	default:
    56  		return "", false
    57  	}
    58  }
    59  
    60  // ReadTime try read time.Time stored in context.Context identified by key.
    61  func ReadTime(ctx context.Context, key interface{}) (time.Time, bool) {
    62  	v := ctx.Value(key)
    63  	if v == nil {
    64  		return time.Time{}, false
    65  	}
    66  	switch i := v.(type) {
    67  	case time.Time:
    68  		return i, true
    69  	case *time.Time:
    70  		return *i, true
    71  	default:
    72  		return time.Time{}, false
    73  	}
    74  }