gin/binding/decimal.go
aydinomer00 fbd60bfe6b feat(binding): add CustomDecimal type for parsing decimal numbers with leading dot
This commit adds support for parsing decimal numbers that start with a dot
(e.g. '.1') in query parameters and form data. It implements the
BindUnmarshaler interface to handle this special case.

Fixes #4089
2025-01-03 11:55:56 +03:00

30 lines
696 B
Go

package binding
import (
"github.com/shopspring/decimal"
"strings"
)
// CustomDecimal represents a decimal number that can be bound from form values.
// It supports values with leading dots (e.g. ".1" is parsed as "0.1").
type CustomDecimal struct {
decimal.Decimal
}
// UnmarshalParam implements the binding.BindUnmarshaler interface.
// It converts form values to decimal.Decimal, with special handling for
// values that start with a dot (e.g. ".1" becomes "0.1").
func (cd *CustomDecimal) UnmarshalParam(val string) error {
if strings.HasPrefix(val, ".") {
val = "0" + val
}
dec, err := decimal.NewFromString(val)
if err != nil {
return err
}
cd.Decimal = dec
return nil
}