github.com/hyperledger/aries-framework-go@v0.3.2/pkg/common/utils/mapstruct.go (about)

     1  /*
     2  Copyright SecureKey Technologies Inc. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package utils
     8  
     9  import (
    10  	"fmt"
    11  	"reflect"
    12  	"strconv"
    13  	"strings"
    14  	"time"
    15  
    16  	"github.com/go-jose/go-jose/v3/jwt"
    17  	"github.com/mitchellh/mapstructure"
    18  )
    19  
    20  // JSONNumberToJwtNumericDate hook for mapstructure library to decode json.Number to jwt.NumericDate.
    21  func JSONNumberToJwtNumericDate() mapstructure.DecodeHookFuncType {
    22  	return func(
    23  		f reflect.Type,
    24  		t reflect.Type,
    25  		data interface{},
    26  	) (interface{}, error) {
    27  		if f.String() != "json.Number" || !strings.Contains("jwt.NumericDate", t.String()) {
    28  			return data, nil
    29  		}
    30  
    31  		parsedFloat, err := strconv.ParseFloat(fmt.Sprint(data), 64)
    32  		if err != nil {
    33  			return nil, err
    34  		}
    35  
    36  		date := jwt.NewNumericDate(time.Unix(int64(parsedFloat), 0))
    37  
    38  		if t.String() == "jwt.NumericDate" {
    39  			return date, nil
    40  		}
    41  
    42  		return &date, nil
    43  	}
    44  }