1 // Copyright 2016 Google LLC.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4 5 package gensupport
6 7 import (
8 "encoding/json"
9 "errors"
10 "fmt"
11 "math"
12 )
13 14 // JSONFloat64 is a float64 that supports proper unmarshaling of special float
15 // values in JSON, according to
16 // https://developers.google.com/protocol-buffers/docs/proto3#json. Although
17 // that is a proto-to-JSON spec, it applies to all Google APIs.
18 //
19 // The jsonpb package
20 // (https://github.com/golang/protobuf/blob/master/jsonpb/jsonpb.go) has
21 // similar functionality, but only for direct translation from proto messages
22 // to JSON.
23 type JSONFloat64 float64
24 25 func (f *JSONFloat64) UnmarshalJSON(data []byte) error {
26 var ff float64
27 if err := json.Unmarshal(data, &ff); err == nil {
28 *f = JSONFloat64(ff)
29 return nil
30 }
31 var s string
32 if err := json.Unmarshal(data, &s); err == nil {
33 switch s {
34 case "NaN":
35 ff = math.NaN()
36 case "Infinity":
37 ff = math.Inf(1)
38 case "-Infinity":
39 ff = math.Inf(-1)
40 default:
41 return fmt.Errorf("google.golang.org/api/internal: bad float string %q", s)
42 }
43 *f = JSONFloat64(ff)
44 return nil
45 }
46 return errors.New("google.golang.org/api/internal: data not float or string")
47 }
48