...

Source file src/go.etcd.io/etcd/client/v2/json.go

Documentation: go.etcd.io/etcd/client/v2

     1  // Copyright 2019 The etcd Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package client
    16  
    17  import (
    18  	"strconv"
    19  	"unsafe"
    20  
    21  	"github.com/json-iterator/go"
    22  	"github.com/modern-go/reflect2"
    23  )
    24  
    25  type customNumberExtension struct {
    26  	jsoniter.DummyExtension
    27  }
    28  
    29  func (cne *customNumberExtension) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {
    30  	if typ.String() == "interface {}" {
    31  		return customNumberDecoder{}
    32  	}
    33  	return nil
    34  }
    35  
    36  type customNumberDecoder struct {
    37  }
    38  
    39  func (customNumberDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
    40  	switch iter.WhatIsNext() {
    41  	case jsoniter.NumberValue:
    42  		var number jsoniter.Number
    43  		iter.ReadVal(&number)
    44  		i64, err := strconv.ParseInt(string(number), 10, 64)
    45  		if err == nil {
    46  			*(*interface{})(ptr) = i64
    47  			return
    48  		}
    49  		f64, err := strconv.ParseFloat(string(number), 64)
    50  		if err == nil {
    51  			*(*interface{})(ptr) = f64
    52  			return
    53  		}
    54  		iter.ReportError("DecodeNumber", err.Error())
    55  	default:
    56  		*(*interface{})(ptr) = iter.Read()
    57  	}
    58  }
    59  
    60  // caseSensitiveJsonIterator returns a jsoniterator API that's configured to be
    61  // case-sensitive when unmarshalling, and otherwise compatible with
    62  // the encoding/json standard library.
    63  func caseSensitiveJsonIterator() jsoniter.API {
    64  	config := jsoniter.Config{
    65  		EscapeHTML:             true,
    66  		SortMapKeys:            true,
    67  		ValidateJsonRawMessage: true,
    68  		CaseSensitive:          true,
    69  	}.Froze()
    70  	// Force jsoniter to decode number to interface{} via int64/float64, if possible.
    71  	config.RegisterExtension(&customNumberExtension{})
    72  	return config
    73  }
    74  

View as plain text