github.com/ethersphere/bee/v2@v2.2.0/pkg/sctx/sctx.go (about)

     1  // Copyright 2020 The Swarm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package sctx provides convenience methods for context
     6  // value injection and extraction.
     7  package sctx
     8  
     9  import (
    10  	"context"
    11  	"errors"
    12  	"math/big"
    13  )
    14  
    15  var (
    16  	// ErrTargetPrefix is returned when target prefix decoding fails.
    17  	ErrTargetPrefix = errors.New("error decoding prefix string")
    18  )
    19  
    20  type (
    21  	HTTPRequestIDKey struct{}
    22  	requestHostKey   struct{}
    23  	gasPriceKey      struct{}
    24  	gasLimitKey      struct{}
    25  )
    26  
    27  // SetHost sets the http request host in the context
    28  func SetHost(ctx context.Context, domain string) context.Context {
    29  	return context.WithValue(ctx, requestHostKey{}, domain)
    30  }
    31  
    32  // GetHost gets the request host from the context
    33  func GetHost(ctx context.Context) string {
    34  	v, ok := ctx.Value(requestHostKey{}).(string)
    35  	if ok {
    36  		return v
    37  	}
    38  	return ""
    39  }
    40  
    41  func SetGasLimit(ctx context.Context, limit uint64) context.Context {
    42  	return context.WithValue(ctx, gasLimitKey{}, limit)
    43  }
    44  
    45  func GetGasLimit(ctx context.Context) uint64 {
    46  	v, ok := ctx.Value(gasLimitKey{}).(uint64)
    47  	if ok {
    48  		return v
    49  	}
    50  	return 0
    51  }
    52  
    53  func GetGasLimitWithDefault(ctx context.Context, defaultLimit uint64) uint64 {
    54  	limit := GetGasLimit(ctx)
    55  	if limit == 0 {
    56  		return defaultLimit
    57  	}
    58  	return limit
    59  }
    60  
    61  func SetGasPrice(ctx context.Context, price *big.Int) context.Context {
    62  	return context.WithValue(ctx, gasPriceKey{}, price)
    63  
    64  }
    65  
    66  func GetGasPrice(ctx context.Context) *big.Int {
    67  	v, ok := ctx.Value(gasPriceKey{}).(*big.Int)
    68  	if ok {
    69  		return v
    70  	}
    71  	return nil
    72  }