1// Copyright 2016 Google LLC 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 15package gensupport 16 17import ( 18 "encoding/json" 19 "errors" 20 "fmt" 21 "math" 22) 23 24// JSONFloat64 is a float64 that supports proper unmarshaling of special float 25// values in JSON, according to 26// https://developers.google.com/protocol-buffers/docs/proto3#json. Although 27// that is a proto-to-JSON spec, it applies to all Google APIs. 28// 29// The jsonpb package 30// (https://github.com/golang/protobuf/blob/master/jsonpb/jsonpb.go) has 31// similar functionality, but only for direct translation from proto messages 32// to JSON. 33type JSONFloat64 float64 34 35func (f *JSONFloat64) UnmarshalJSON(data []byte) error { 36 var ff float64 37 if err := json.Unmarshal(data, &ff); err == nil { 38 *f = JSONFloat64(ff) 39 return nil 40 } 41 var s string 42 if err := json.Unmarshal(data, &s); err == nil { 43 switch s { 44 case "NaN": 45 ff = math.NaN() 46 case "Infinity": 47 ff = math.Inf(1) 48 case "-Infinity": 49 ff = math.Inf(-1) 50 default: 51 return fmt.Errorf("google.golang.org/api/internal: bad float string %q", s) 52 } 53 *f = JSONFloat64(ff) 54 return nil 55 } 56 return errors.New("google.golang.org/api/internal: data not float or string") 57} 58