-
Notifications
You must be signed in to change notification settings - Fork 47
/
parse.go
98 lines (85 loc) · 1.84 KB
/
parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
package configutil
import (
"context"
"strconv"
"time"
"github.com/blend/go-sdk/ex"
"github.com/blend/go-sdk/stringutil"
)
var (
_ IntSource = (*Parser)(nil)
_ Float64Source = (*Parser)(nil)
_ DurationSource = (*Parser)(nil)
)
// Parse returns an int parser.
func Parse(source StringSource) Parser {
return Parser{Source: source}
}
// Parser parses an int.
type Parser struct {
Source StringSource
}
// Bool returns the bool value.
func (p Parser) Bool(ctx context.Context) (*bool, error) {
value, err := p.Source.String(ctx)
if err != nil {
return nil, err
}
if value == nil {
return nil, nil
}
parsed, err := stringutil.ParseBool(*value)
if err != nil {
return nil, err
}
return &parsed, nil
}
// Int returns the int value.
func (p Parser) Int(ctx context.Context) (*int, error) {
value, err := p.Source.String(ctx)
if err != nil {
return nil, err
}
if value == nil {
return nil, nil
}
parsed, err := strconv.Atoi(*value)
if err != nil {
return nil, ex.New(err)
}
return &parsed, nil
}
// Float64 returns the float64 value.
func (p Parser) Float64(ctx context.Context) (*float64, error) {
value, err := p.Source.String(ctx)
if err != nil {
return nil, err
}
if value == nil {
return nil, nil
}
parsed, err := strconv.ParseFloat(*value, 64)
if err != nil {
return nil, ex.New(err)
}
return &parsed, nil
}
// Duration returns a parsed duration value.
func (p Parser) Duration(ctx context.Context) (*time.Duration, error) {
value, err := p.Source.String(ctx)
if err != nil {
return nil, err
}
if value == nil {
return nil, nil
}
parsed, err := time.ParseDuration(*value)
if err != nil {
return nil, ex.New(err)
}
return &parsed, nil
}