github.com/easysoft/zendata@v0.0.0-20240513203326-705bd5a7fd67/internal/pkg/service/format.go (about)

     1  package service
     2  
     3  import (
     4  	"log"
     5  	"regexp"
     6  	"strconv"
     7  	"strings"
     8  	"time"
     9  
    10  	consts "github.com/easysoft/zendata/internal/pkg/const"
    11  	"github.com/easysoft/zendata/internal/pkg/domain"
    12  	"github.com/easysoft/zendata/internal/pkg/helper"
    13  )
    14  
    15  type FormatService struct {
    16  }
    17  
    18  func (s *FormatService) GetFieldValStr(field domain.DefField, val interface{}) interface{} {
    19  	str := consts.Na
    20  	success := false
    21  
    22  	format := strings.TrimSpace(field.Format)
    23  
    24  	if field.Type == consts.FieldTypeTimestamp && format != "" {
    25  		str = time.Unix(val.(int64), 0).Format(format)
    26  		return str
    27  	}
    28  
    29  	switch val.(type) {
    30  	case int64:
    31  		if format == "" {
    32  			return val
    33  		}
    34  
    35  		str, success = helper.FormatStr(format, val.(int64), 0)
    36  		if !success {
    37  			str = strconv.FormatInt(val.(int64), 10)
    38  		}
    39  		return str
    40  
    41  	case float64:
    42  		if field.Precision == 0 && format == "" {
    43  			return val
    44  		}
    45  
    46  		precision := 0
    47  		if field.Precision > 0 {
    48  			precision = field.Precision
    49  		}
    50  		if format != "" {
    51  			str, success = helper.FormatStr(format, val.(float64), precision)
    52  		}
    53  		if !success {
    54  			str = strconv.FormatFloat(val.(float64), 'f', precision, 64)
    55  		}
    56  
    57  	case byte:
    58  		str = string(val.(byte))
    59  		if format != "" {
    60  			str, success = helper.FormatStr(format, str, 0)
    61  		}
    62  		if !success {
    63  			str = string(val.(byte))
    64  		}
    65  
    66  	case string:
    67  		str = val.(string)
    68  
    69  		match, _ := regexp.MatchString("%[0-9]*d", format)
    70  		if match {
    71  			valInt, err := strconv.Atoi(str)
    72  			if err == nil {
    73  				str, success = helper.FormatStr(format, valInt, 0)
    74  			}
    75  		} else {
    76  			str, success = helper.FormatStr(format, str, 0)
    77  		}
    78  	default:
    79  	}
    80  
    81  	if str == consts.Na {
    82  		log.Println(str)
    83  	}
    84  
    85  	return str
    86  }