github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/httplib/uint64_list.go (about)

     1  package httplib
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"strconv"
     7  	"strings"
     8  )
     9  
    10  type Uint64List []uint64
    11  
    12  func (list Uint64List) MarshalJSON() ([]byte, error) {
    13  	if len(list) == 0 {
    14  		return []byte(`[]`), nil
    15  	}
    16  	strValues := make([]string, 0)
    17  	for _, v := range list {
    18  		strValues = append(strValues, fmt.Sprintf(`"%d"`, v))
    19  	}
    20  	return []byte(`[` + strings.Join(strValues, ",") + `]`), nil
    21  }
    22  
    23  func (list *Uint64List) UnmarshalJSON(data []byte) (err error) {
    24  	strValues := make([]string, 0)
    25  	err = json.Unmarshal(data, &strValues)
    26  	if err != nil {
    27  		return err
    28  	}
    29  	finalList := Uint64List{}
    30  	for i, strValue := range strValues {
    31  		v, parseErr := strconv.ParseUint(strValue, 10, 64)
    32  		if parseErr != nil {
    33  			err = fmt.Errorf(`[%d] cannot unmarshal string into value of type uint64`, i)
    34  			return
    35  		}
    36  		finalList = append(finalList, v)
    37  	}
    38  	*list = finalList
    39  	return
    40  }