decred.org/dcrwallet/v3@v3.1.0/internal/cfgutil/amount.go (about) 1 // Copyright (c) 2015-2016 The btcsuite developers 2 // Copyright (c) 2016 The Decred developers 3 // Use of this source code is governed by an ISC 4 // license that can be found in the LICENSE file. 5 6 package cfgutil 7 8 import ( 9 "strconv" 10 "strings" 11 12 "github.com/decred/dcrd/dcrutil/v4" 13 ) 14 15 // AmountFlag embeds a dcrutil.Amount and implements the flags.Marshaler and 16 // Unmarshaler interfaces so it can be used as a config struct field. 17 type AmountFlag struct { 18 dcrutil.Amount 19 } 20 21 // NewAmountFlag creates an AmountFlag with a default dcrutil.Amount. 22 func NewAmountFlag(defaultValue dcrutil.Amount) *AmountFlag { 23 return &AmountFlag{defaultValue} 24 } 25 26 // MarshalFlag satisfies the flags.Marshaler interface. 27 func (a *AmountFlag) MarshalFlag() (string, error) { 28 return a.Amount.String(), nil 29 } 30 31 // UnmarshalFlag satisfies the flags.Unmarshaler interface. 32 func (a *AmountFlag) UnmarshalFlag(value string) error { 33 value = strings.TrimSuffix(value, " DCR") 34 valueF64, err := strconv.ParseFloat(value, 64) 35 if err != nil { 36 return err 37 } 38 amount, err := dcrutil.NewAmount(valueF64) 39 if err != nil { 40 return err 41 } 42 a.Amount = amount 43 return nil 44 }