github.com/blend/go-sdk@v1.20220411.3/configutil/parse.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 configutil
     9  
    10  import (
    11  	"context"
    12  	"strconv"
    13  	"time"
    14  
    15  	"github.com/blend/go-sdk/ex"
    16  	"github.com/blend/go-sdk/stringutil"
    17  )
    18  
    19  var (
    20  	_ IntSource      = (*Parser)(nil)
    21  	_ Float64Source  = (*Parser)(nil)
    22  	_ DurationSource = (*Parser)(nil)
    23  )
    24  
    25  // Parse returns an int parser.
    26  func Parse(source StringSource) Parser {
    27  	return Parser{Source: source}
    28  }
    29  
    30  // Parser parses an int.
    31  type Parser struct {
    32  	Source StringSource
    33  }
    34  
    35  // Bool returns the bool value.
    36  func (p Parser) Bool(ctx context.Context) (*bool, error) {
    37  	value, err := p.Source.String(ctx)
    38  	if err != nil {
    39  		return nil, err
    40  	}
    41  	if value == nil {
    42  		return nil, nil
    43  	}
    44  
    45  	parsed, err := stringutil.ParseBool(*value)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	return &parsed, nil
    50  }
    51  
    52  // Int returns the int value.
    53  func (p Parser) Int(ctx context.Context) (*int, error) {
    54  	value, err := p.Source.String(ctx)
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  	if value == nil {
    59  		return nil, nil
    60  	}
    61  	parsed, err := strconv.Atoi(*value)
    62  	if err != nil {
    63  		return nil, ex.New(err)
    64  	}
    65  	return &parsed, nil
    66  }
    67  
    68  // Float64 returns the float64 value.
    69  func (p Parser) Float64(ctx context.Context) (*float64, error) {
    70  	value, err := p.Source.String(ctx)
    71  	if err != nil {
    72  		return nil, err
    73  	}
    74  	if value == nil {
    75  		return nil, nil
    76  	}
    77  	parsed, err := strconv.ParseFloat(*value, 64)
    78  	if err != nil {
    79  		return nil, ex.New(err)
    80  	}
    81  	return &parsed, nil
    82  }
    83  
    84  // Duration returns a parsed duration value.
    85  func (p Parser) Duration(ctx context.Context) (*time.Duration, error) {
    86  	value, err := p.Source.String(ctx)
    87  	if err != nil {
    88  		return nil, err
    89  	}
    90  	if value == nil {
    91  		return nil, nil
    92  	}
    93  	parsed, err := time.ParseDuration(*value)
    94  	if err != nil {
    95  		return nil, ex.New(err)
    96  	}
    97  	return &parsed, nil
    98  }