convert.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package runtime
  2. import (
  3. "strconv"
  4. "github.com/golang/protobuf/jsonpb"
  5. "github.com/golang/protobuf/ptypes/duration"
  6. "github.com/golang/protobuf/ptypes/timestamp"
  7. )
  8. // String just returns the given string.
  9. // It is just for compatibility to other types.
  10. func String(val string) (string, error) {
  11. return val, nil
  12. }
  13. // Bool converts the given string representation of a boolean value into bool.
  14. func Bool(val string) (bool, error) {
  15. return strconv.ParseBool(val)
  16. }
  17. // Float64 converts the given string representation into representation of a floating point number into float64.
  18. func Float64(val string) (float64, error) {
  19. return strconv.ParseFloat(val, 64)
  20. }
  21. // Float32 converts the given string representation of a floating point number into float32.
  22. func Float32(val string) (float32, error) {
  23. f, err := strconv.ParseFloat(val, 32)
  24. if err != nil {
  25. return 0, err
  26. }
  27. return float32(f), nil
  28. }
  29. // Int64 converts the given string representation of an integer into int64.
  30. func Int64(val string) (int64, error) {
  31. return strconv.ParseInt(val, 0, 64)
  32. }
  33. // Int32 converts the given string representation of an integer into int32.
  34. func Int32(val string) (int32, error) {
  35. i, err := strconv.ParseInt(val, 0, 32)
  36. if err != nil {
  37. return 0, err
  38. }
  39. return int32(i), nil
  40. }
  41. // Uint64 converts the given string representation of an integer into uint64.
  42. func Uint64(val string) (uint64, error) {
  43. return strconv.ParseUint(val, 0, 64)
  44. }
  45. // Uint32 converts the given string representation of an integer into uint32.
  46. func Uint32(val string) (uint32, error) {
  47. i, err := strconv.ParseUint(val, 0, 32)
  48. if err != nil {
  49. return 0, err
  50. }
  51. return uint32(i), nil
  52. }
  53. // Timestamp converts the given RFC3339 formatted string into a timestamp.Timestamp.
  54. func Timestamp(val string) (*timestamp.Timestamp, error) {
  55. var r *timestamp.Timestamp
  56. err := jsonpb.UnmarshalString(val, r)
  57. return r, err
  58. }
  59. // Duration converts the given string into a timestamp.Duration.
  60. func Duration(val string) (*duration.Duration, error) {
  61. var r *duration.Duration
  62. err := jsonpb.UnmarshalString(val, r)
  63. return r, err
  64. }