github.com/tanqiangyes/govalidator@v0.0.5/converter.go (about)

     1  package govalidator
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"reflect"
     7  	"strconv"
     8  
     9  	"golang.org/x/exp/constraints"
    10  )
    11  
    12  // ToString convert the input to a string.
    13  func ToString[T any](obj T) string {
    14  	res := fmt.Sprintf("%v", obj)
    15  	return res
    16  }
    17  
    18  // ToJSON convert the input to a valid JSON string
    19  func ToJSON[T any](obj T) (string, error) {
    20  	res, err := json.Marshal(obj)
    21  	if err != nil {
    22  		res = []byte("")
    23  	}
    24  	return string(res), err
    25  }
    26  
    27  // ToNumber convert the input string to a number, or 0.0 if the input is not a number.
    28  func ToNumber[T any, U constraints.Float | constraints.Integer](value T) (res U, err error) {
    29  	val := reflect.ValueOf(value)
    30  
    31  	switch val.Kind() {
    32  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
    33  		res = U(val.Int())
    34  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
    35  		res = U(val.Uint())
    36  	case reflect.Float32, reflect.Float64:
    37  		res = U(val.Float())
    38  	case reflect.String:
    39  		if IsInt[string](val.String()) {
    40  			resInt, err := strconv.ParseInt(val.String(), 0, 64)
    41  			if err != nil {
    42  				res = 0
    43  			} else {
    44  				res = U(resInt)
    45  			}
    46  		} else if resFloat, err := strconv.ParseFloat(val.String(), 64); err == nil {
    47  			res = U(resFloat)
    48  		} else {
    49  			err = fmt.Errorf("ToInt: invalid numeric format %v", value)
    50  			res = 0
    51  		}
    52  
    53  	default:
    54  		err = fmt.Errorf("ToInt: unknown interface type %T", value)
    55  		res = 0
    56  	}
    57  
    58  	return
    59  }
    60  
    61  // ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer.
    62  func ToInt[T any](value T) (res int64, err error) {
    63  	return ToNumber[any, int64](value)
    64  }
    65  
    66  // ToBoolean convert the input string to a boolean.
    67  func ToBoolean[T ~string](str T) (bool, error) {
    68  	return strconv.ParseBool(string(str))
    69  }