convert.go 2.4 KB

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