jsonfloat.go 1.2 KB

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