在Go中轻松安全地从一种数据类型转换为另一种数据类型
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1311 lines
30 KiB

  1. // Copyright © 2014 Steve Francia <spf@spf13.com>.
  2. //
  3. // Use of this source code is governed by an MIT-style
  4. // license that can be found in the LICENSE file.
  5. package cast
  6. import (
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "html/template"
  11. "reflect"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. var errNegativeNotAllowed = errors.New("unable to cast negative value")
  17. // ToTimeE casts an interface to a time.Time type.
  18. func ToTimeE(i interface{}) (tim time.Time, err error) {
  19. return ToTimeInDefaultLocationE(i, nil)
  20. }
  21. // ToTimeInDefaultLocationE casts an empty interface to time.Time,
  22. // interpreting inputs without a timezone to be in the given location.
  23. // To fall back to the local timezone, use time.Local as the last argument.
  24. func ToTimeInDefaultLocationE(i interface{}, location *time.Location) (tim time.Time, err error) {
  25. i = indirect(i)
  26. switch v := i.(type) {
  27. case time.Time:
  28. return v, nil
  29. case string:
  30. return StringToDateInDefaultLocation(v, location)
  31. case int:
  32. return time.Unix(int64(v), 0), nil
  33. case int64:
  34. return time.Unix(v, 0), nil
  35. case int32:
  36. return time.Unix(int64(v), 0), nil
  37. case uint:
  38. return time.Unix(int64(v), 0), nil
  39. case uint64:
  40. return time.Unix(int64(v), 0), nil
  41. case uint32:
  42. return time.Unix(int64(v), 0), nil
  43. default:
  44. return time.Time{}, fmt.Errorf("unable to cast %#v of type %T to Time", i, i)
  45. }
  46. }
  47. // ToDurationE casts an interface to a time.Duration type.
  48. func ToDurationE(i interface{}) (d time.Duration, err error) {
  49. i = indirect(i)
  50. switch s := i.(type) {
  51. case time.Duration:
  52. return s, nil
  53. case int, int64, int32, int16, int8, uint, uint64, uint32, uint16, uint8:
  54. d = time.Duration(ToInt64(s))
  55. return
  56. case float32, float64:
  57. d = time.Duration(ToFloat64(s))
  58. return
  59. case string:
  60. if strings.ContainsAny(s, "nsuµmh") {
  61. d, err = time.ParseDuration(s)
  62. } else {
  63. d, err = time.ParseDuration(s + "ns")
  64. }
  65. return
  66. default:
  67. err = fmt.Errorf("unable to cast %#v of type %T to Duration", i, i)
  68. return
  69. }
  70. }
  71. // ToBoolE casts an interface to a bool type.
  72. func ToBoolE(i interface{}) (bool, error) {
  73. i = indirect(i)
  74. switch b := i.(type) {
  75. case bool:
  76. return b, nil
  77. case nil:
  78. return false, nil
  79. case int:
  80. if i.(int) != 0 {
  81. return true, nil
  82. }
  83. return false, nil
  84. case string:
  85. return strconv.ParseBool(i.(string))
  86. default:
  87. return false, fmt.Errorf("unable to cast %#v of type %T to bool", i, i)
  88. }
  89. }
  90. // ToFloat64E casts an interface to a float64 type.
  91. func ToFloat64E(i interface{}) (float64, error) {
  92. i = indirect(i)
  93. switch s := i.(type) {
  94. case float64:
  95. return s, nil
  96. case float32:
  97. return float64(s), nil
  98. case int:
  99. return float64(s), nil
  100. case int64:
  101. return float64(s), nil
  102. case int32:
  103. return float64(s), nil
  104. case int16:
  105. return float64(s), nil
  106. case int8:
  107. return float64(s), nil
  108. case uint:
  109. return float64(s), nil
  110. case uint64:
  111. return float64(s), nil
  112. case uint32:
  113. return float64(s), nil
  114. case uint16:
  115. return float64(s), nil
  116. case uint8:
  117. return float64(s), nil
  118. case string:
  119. v, err := strconv.ParseFloat(s, 64)
  120. if err == nil {
  121. return v, nil
  122. }
  123. return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i)
  124. case bool:
  125. if s {
  126. return 1, nil
  127. }
  128. return 0, nil
  129. default:
  130. return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i)
  131. }
  132. }
  133. // ToFloat32E casts an interface to a float32 type.
  134. func ToFloat32E(i interface{}) (float32, error) {
  135. i = indirect(i)
  136. switch s := i.(type) {
  137. case float64:
  138. return float32(s), nil
  139. case float32:
  140. return s, nil
  141. case int:
  142. return float32(s), nil
  143. case int64:
  144. return float32(s), nil
  145. case int32:
  146. return float32(s), nil
  147. case int16:
  148. return float32(s), nil
  149. case int8:
  150. return float32(s), nil
  151. case uint:
  152. return float32(s), nil
  153. case uint64:
  154. return float32(s), nil
  155. case uint32:
  156. return float32(s), nil
  157. case uint16:
  158. return float32(s), nil
  159. case uint8:
  160. return float32(s), nil
  161. case string:
  162. v, err := strconv.ParseFloat(s, 32)
  163. if err == nil {
  164. return float32(v), nil
  165. }
  166. return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i)
  167. case bool:
  168. if s {
  169. return 1, nil
  170. }
  171. return 0, nil
  172. default:
  173. return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i)
  174. }
  175. }
  176. // ToInt64E casts an interface to an int64 type.
  177. func ToInt64E(i interface{}) (int64, error) {
  178. i = indirect(i)
  179. switch s := i.(type) {
  180. case int:
  181. return int64(s), nil
  182. case int64:
  183. return s, nil
  184. case int32:
  185. return int64(s), nil
  186. case int16:
  187. return int64(s), nil
  188. case int8:
  189. return int64(s), nil
  190. case uint:
  191. return int64(s), nil
  192. case uint64:
  193. return int64(s), nil
  194. case uint32:
  195. return int64(s), nil
  196. case uint16:
  197. return int64(s), nil
  198. case uint8:
  199. return int64(s), nil
  200. case float64:
  201. return int64(s), nil
  202. case float32:
  203. return int64(s), nil
  204. case string:
  205. v, err := strconv.ParseInt(s, 0, 0)
  206. if err == nil {
  207. return v, nil
  208. }
  209. return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i)
  210. case bool:
  211. if s {
  212. return 1, nil
  213. }
  214. return 0, nil
  215. case nil:
  216. return 0, nil
  217. default:
  218. return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i)
  219. }
  220. }
  221. // ToInt32E casts an interface to an int32 type.
  222. func ToInt32E(i interface{}) (int32, error) {
  223. i = indirect(i)
  224. switch s := i.(type) {
  225. case int:
  226. return int32(s), nil
  227. case int64:
  228. return int32(s), nil
  229. case int32:
  230. return s, nil
  231. case int16:
  232. return int32(s), nil
  233. case int8:
  234. return int32(s), nil
  235. case uint:
  236. return int32(s), nil
  237. case uint64:
  238. return int32(s), nil
  239. case uint32:
  240. return int32(s), nil
  241. case uint16:
  242. return int32(s), nil
  243. case uint8:
  244. return int32(s), nil
  245. case float64:
  246. return int32(s), nil
  247. case float32:
  248. return int32(s), nil
  249. case string:
  250. v, err := strconv.ParseInt(s, 0, 0)
  251. if err == nil {
  252. return int32(v), nil
  253. }
  254. return 0, fmt.Errorf("unable to cast %#v of type %T to int32", i, i)
  255. case bool:
  256. if s {
  257. return 1, nil
  258. }
  259. return 0, nil
  260. case nil:
  261. return 0, nil
  262. default:
  263. return 0, fmt.Errorf("unable to cast %#v of type %T to int32", i, i)
  264. }
  265. }
  266. // ToInt16E casts an interface to an int16 type.
  267. func ToInt16E(i interface{}) (int16, error) {
  268. i = indirect(i)
  269. switch s := i.(type) {
  270. case int:
  271. return int16(s), nil
  272. case int64:
  273. return int16(s), nil
  274. case int32:
  275. return int16(s), nil
  276. case int16:
  277. return s, nil
  278. case int8:
  279. return int16(s), nil
  280. case uint:
  281. return int16(s), nil
  282. case uint64:
  283. return int16(s), nil
  284. case uint32:
  285. return int16(s), nil
  286. case uint16:
  287. return int16(s), nil
  288. case uint8:
  289. return int16(s), nil
  290. case float64:
  291. return int16(s), nil
  292. case float32:
  293. return int16(s), nil
  294. case string:
  295. v, err := strconv.ParseInt(s, 0, 0)
  296. if err == nil {
  297. return int16(v), nil
  298. }
  299. return 0, fmt.Errorf("unable to cast %#v of type %T to int16", i, i)
  300. case bool:
  301. if s {
  302. return 1, nil
  303. }
  304. return 0, nil
  305. case nil:
  306. return 0, nil
  307. default:
  308. return 0, fmt.Errorf("unable to cast %#v of type %T to int16", i, i)
  309. }
  310. }
  311. // ToInt8E casts an interface to an int8 type.
  312. func ToInt8E(i interface{}) (int8, error) {
  313. i = indirect(i)
  314. switch s := i.(type) {
  315. case int:
  316. return int8(s), nil
  317. case int64:
  318. return int8(s), nil
  319. case int32:
  320. return int8(s), nil
  321. case int16:
  322. return int8(s), nil
  323. case int8:
  324. return s, nil
  325. case uint:
  326. return int8(s), nil
  327. case uint64:
  328. return int8(s), nil
  329. case uint32:
  330. return int8(s), nil
  331. case uint16:
  332. return int8(s), nil
  333. case uint8:
  334. return int8(s), nil
  335. case float64:
  336. return int8(s), nil
  337. case float32:
  338. return int8(s), nil
  339. case string:
  340. v, err := strconv.ParseInt(s, 0, 0)
  341. if err == nil {
  342. return int8(v), nil
  343. }
  344. return 0, fmt.Errorf("unable to cast %#v of type %T to int8", i, i)
  345. case bool:
  346. if s {
  347. return 1, nil
  348. }
  349. return 0, nil
  350. case nil:
  351. return 0, nil
  352. default:
  353. return 0, fmt.Errorf("unable to cast %#v of type %T to int8", i, i)
  354. }
  355. }
  356. // ToIntE casts an interface to an int type.
  357. func ToIntE(i interface{}) (int, error) {
  358. i = indirect(i)
  359. switch s := i.(type) {
  360. case int:
  361. return s, nil
  362. case int64:
  363. return int(s), nil
  364. case int32:
  365. return int(s), nil
  366. case int16:
  367. return int(s), nil
  368. case int8:
  369. return int(s), nil
  370. case uint:
  371. return int(s), nil
  372. case uint64:
  373. return int(s), nil
  374. case uint32:
  375. return int(s), nil
  376. case uint16:
  377. return int(s), nil
  378. case uint8:
  379. return int(s), nil
  380. case float64:
  381. return int(s), nil
  382. case float32:
  383. return int(s), nil
  384. case string:
  385. v, err := strconv.ParseInt(s, 0, 0)
  386. if err == nil {
  387. return int(v), nil
  388. }
  389. return 0, fmt.Errorf("unable to cast %#v of type %T to int", i, i)
  390. case bool:
  391. if s {
  392. return 1, nil
  393. }
  394. return 0, nil
  395. case nil:
  396. return 0, nil
  397. default:
  398. return 0, fmt.Errorf("unable to cast %#v of type %T to int", i, i)
  399. }
  400. }
  401. // ToUintE casts an interface to a uint type.
  402. func ToUintE(i interface{}) (uint, error) {
  403. i = indirect(i)
  404. switch s := i.(type) {
  405. case string:
  406. v, err := strconv.ParseUint(s, 0, 0)
  407. if err == nil {
  408. return uint(v), nil
  409. }
  410. return 0, fmt.Errorf("unable to cast %#v to uint: %s", i, err)
  411. case int:
  412. if s < 0 {
  413. return 0, errNegativeNotAllowed
  414. }
  415. return uint(s), nil
  416. case int64:
  417. if s < 0 {
  418. return 0, errNegativeNotAllowed
  419. }
  420. return uint(s), nil
  421. case int32:
  422. if s < 0 {
  423. return 0, errNegativeNotAllowed
  424. }
  425. return uint(s), nil
  426. case int16:
  427. if s < 0 {
  428. return 0, errNegativeNotAllowed
  429. }
  430. return uint(s), nil
  431. case int8:
  432. if s < 0 {
  433. return 0, errNegativeNotAllowed
  434. }
  435. return uint(s), nil
  436. case uint:
  437. return s, nil
  438. case uint64:
  439. return uint(s), nil
  440. case uint32:
  441. return uint(s), nil
  442. case uint16:
  443. return uint(s), nil
  444. case uint8:
  445. return uint(s), nil
  446. case float64:
  447. if s < 0 {
  448. return 0, errNegativeNotAllowed
  449. }
  450. return uint(s), nil
  451. case float32:
  452. if s < 0 {
  453. return 0, errNegativeNotAllowed
  454. }
  455. return uint(s), nil
  456. case bool:
  457. if s {
  458. return 1, nil
  459. }
  460. return 0, nil
  461. case nil:
  462. return 0, nil
  463. default:
  464. return 0, fmt.Errorf("unable to cast %#v of type %T to uint", i, i)
  465. }
  466. }
  467. // ToUint64E casts an interface to a uint64 type.
  468. func ToUint64E(i interface{}) (uint64, error) {
  469. i = indirect(i)
  470. switch s := i.(type) {
  471. case string:
  472. v, err := strconv.ParseUint(s, 0, 64)
  473. if err == nil {
  474. return v, nil
  475. }
  476. return 0, fmt.Errorf("unable to cast %#v to uint64: %s", i, err)
  477. case int:
  478. if s < 0 {
  479. return 0, errNegativeNotAllowed
  480. }
  481. return uint64(s), nil
  482. case int64:
  483. if s < 0 {
  484. return 0, errNegativeNotAllowed
  485. }
  486. return uint64(s), nil
  487. case int32:
  488. if s < 0 {
  489. return 0, errNegativeNotAllowed
  490. }
  491. return uint64(s), nil
  492. case int16:
  493. if s < 0 {
  494. return 0, errNegativeNotAllowed
  495. }
  496. return uint64(s), nil
  497. case int8:
  498. if s < 0 {
  499. return 0, errNegativeNotAllowed
  500. }
  501. return uint64(s), nil
  502. case uint:
  503. return uint64(s), nil
  504. case uint64:
  505. return s, nil
  506. case uint32:
  507. return uint64(s), nil
  508. case uint16:
  509. return uint64(s), nil
  510. case uint8:
  511. return uint64(s), nil
  512. case float32:
  513. if s < 0 {
  514. return 0, errNegativeNotAllowed
  515. }
  516. return uint64(s), nil
  517. case float64:
  518. if s < 0 {
  519. return 0, errNegativeNotAllowed
  520. }
  521. return uint64(s), nil
  522. case bool:
  523. if s {
  524. return 1, nil
  525. }
  526. return 0, nil
  527. case nil:
  528. return 0, nil
  529. default:
  530. return 0, fmt.Errorf("unable to cast %#v of type %T to uint64", i, i)
  531. }
  532. }
  533. // ToUint32E casts an interface to a uint32 type.
  534. func ToUint32E(i interface{}) (uint32, error) {
  535. i = indirect(i)
  536. switch s := i.(type) {
  537. case string:
  538. v, err := strconv.ParseUint(s, 0, 32)
  539. if err == nil {
  540. return uint32(v), nil
  541. }
  542. return 0, fmt.Errorf("unable to cast %#v to uint32: %s", i, err)
  543. case int:
  544. if s < 0 {
  545. return 0, errNegativeNotAllowed
  546. }
  547. return uint32(s), nil
  548. case int64:
  549. if s < 0 {
  550. return 0, errNegativeNotAllowed
  551. }
  552. return uint32(s), nil
  553. case int32:
  554. if s < 0 {
  555. return 0, errNegativeNotAllowed
  556. }
  557. return uint32(s), nil
  558. case int16:
  559. if s < 0 {
  560. return 0, errNegativeNotAllowed
  561. }
  562. return uint32(s), nil
  563. case int8:
  564. if s < 0 {
  565. return 0, errNegativeNotAllowed
  566. }
  567. return uint32(s), nil
  568. case uint:
  569. return uint32(s), nil
  570. case uint64:
  571. return uint32(s), nil
  572. case uint32:
  573. return s, nil
  574. case uint16:
  575. return uint32(s), nil
  576. case uint8:
  577. return uint32(s), nil
  578. case float64:
  579. if s < 0 {
  580. return 0, errNegativeNotAllowed
  581. }
  582. return uint32(s), nil
  583. case float32:
  584. if s < 0 {
  585. return 0, errNegativeNotAllowed
  586. }
  587. return uint32(s), nil
  588. case bool:
  589. if s {
  590. return 1, nil
  591. }
  592. return 0, nil
  593. case nil:
  594. return 0, nil
  595. default:
  596. return 0, fmt.Errorf("unable to cast %#v of type %T to uint32", i, i)
  597. }
  598. }
  599. // ToUint16E casts an interface to a uint16 type.
  600. func ToUint16E(i interface{}) (uint16, error) {
  601. i = indirect(i)
  602. switch s := i.(type) {
  603. case string:
  604. v, err := strconv.ParseUint(s, 0, 16)
  605. if err == nil {
  606. return uint16(v), nil
  607. }
  608. return 0, fmt.Errorf("unable to cast %#v to uint16: %s", i, err)
  609. case int:
  610. if s < 0 {
  611. return 0, errNegativeNotAllowed
  612. }
  613. return uint16(s), nil
  614. case int64:
  615. if s < 0 {
  616. return 0, errNegativeNotAllowed
  617. }
  618. return uint16(s), nil
  619. case int32:
  620. if s < 0 {
  621. return 0, errNegativeNotAllowed
  622. }
  623. return uint16(s), nil
  624. case int16:
  625. if s < 0 {
  626. return 0, errNegativeNotAllowed
  627. }
  628. return uint16(s), nil
  629. case int8:
  630. if s < 0 {
  631. return 0, errNegativeNotAllowed
  632. }
  633. return uint16(s), nil
  634. case uint:
  635. return uint16(s), nil
  636. case uint64:
  637. return uint16(s), nil
  638. case uint32:
  639. return uint16(s), nil
  640. case uint16:
  641. return s, nil
  642. case uint8:
  643. return uint16(s), nil
  644. case float64:
  645. if s < 0 {
  646. return 0, errNegativeNotAllowed
  647. }
  648. return uint16(s), nil
  649. case float32:
  650. if s < 0 {
  651. return 0, errNegativeNotAllowed
  652. }
  653. return uint16(s), nil
  654. case bool:
  655. if s {
  656. return 1, nil
  657. }
  658. return 0, nil
  659. case nil:
  660. return 0, nil
  661. default:
  662. return 0, fmt.Errorf("unable to cast %#v of type %T to uint16", i, i)
  663. }
  664. }
  665. // ToUint8E casts an interface to a uint type.
  666. func ToUint8E(i interface{}) (uint8, error) {
  667. i = indirect(i)
  668. switch s := i.(type) {
  669. case string:
  670. v, err := strconv.ParseUint(s, 0, 8)
  671. if err == nil {
  672. return uint8(v), nil
  673. }
  674. return 0, fmt.Errorf("unable to cast %#v to uint8: %s", i, err)
  675. case int:
  676. if s < 0 {
  677. return 0, errNegativeNotAllowed
  678. }
  679. return uint8(s), nil
  680. case int64:
  681. if s < 0 {
  682. return 0, errNegativeNotAllowed
  683. }
  684. return uint8(s), nil
  685. case int32:
  686. if s < 0 {
  687. return 0, errNegativeNotAllowed
  688. }
  689. return uint8(s), nil
  690. case int16:
  691. if s < 0 {
  692. return 0, errNegativeNotAllowed
  693. }
  694. return uint8(s), nil
  695. case int8:
  696. if s < 0 {
  697. return 0, errNegativeNotAllowed
  698. }
  699. return uint8(s), nil
  700. case uint:
  701. return uint8(s), nil
  702. case uint64:
  703. return uint8(s), nil
  704. case uint32:
  705. return uint8(s), nil
  706. case uint16:
  707. return uint8(s), nil
  708. case uint8:
  709. return s, nil
  710. case float64:
  711. if s < 0 {
  712. return 0, errNegativeNotAllowed
  713. }
  714. return uint8(s), nil
  715. case float32:
  716. if s < 0 {
  717. return 0, errNegativeNotAllowed
  718. }
  719. return uint8(s), nil
  720. case bool:
  721. if s {
  722. return 1, nil
  723. }
  724. return 0, nil
  725. case nil:
  726. return 0, nil
  727. default:
  728. return 0, fmt.Errorf("unable to cast %#v of type %T to uint8", i, i)
  729. }
  730. }
  731. // From html/template/content.go
  732. // Copyright 2011 The Go Authors. All rights reserved.
  733. // indirect returns the value, after dereferencing as many times
  734. // as necessary to reach the base type (or nil).
  735. func indirect(a interface{}) interface{} {
  736. if a == nil {
  737. return nil
  738. }
  739. if t := reflect.TypeOf(a); t.Kind() != reflect.Ptr {
  740. // Avoid creating a reflect.Value if it's not a pointer.
  741. return a
  742. }
  743. v := reflect.ValueOf(a)
  744. for v.Kind() == reflect.Ptr && !v.IsNil() {
  745. v = v.Elem()
  746. }
  747. return v.Interface()
  748. }
  749. // From html/template/content.go
  750. // Copyright 2011 The Go Authors. All rights reserved.
  751. // indirectToStringerOrError returns the value, after dereferencing as many times
  752. // as necessary to reach the base type (or nil) or an implementation of fmt.Stringer
  753. // or error,
  754. func indirectToStringerOrError(a interface{}) interface{} {
  755. if a == nil {
  756. return nil
  757. }
  758. var errorType = reflect.TypeOf((*error)(nil)).Elem()
  759. var fmtStringerType = reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
  760. v := reflect.ValueOf(a)
  761. for !v.Type().Implements(fmtStringerType) && !v.Type().Implements(errorType) && v.Kind() == reflect.Ptr && !v.IsNil() {
  762. v = v.Elem()
  763. }
  764. return v.Interface()
  765. }
  766. // ToStringE casts an interface to a string type.
  767. func ToStringE(i interface{}) (string, error) {
  768. i = indirectToStringerOrError(i)
  769. switch s := i.(type) {
  770. case string:
  771. return s, nil
  772. case bool:
  773. return strconv.FormatBool(s), nil
  774. case float64:
  775. return strconv.FormatFloat(s, 'f', -1, 64), nil
  776. case float32:
  777. return strconv.FormatFloat(float64(s), 'f', -1, 32), nil
  778. case int:
  779. return strconv.Itoa(s), nil
  780. case int64:
  781. return strconv.FormatInt(s, 10), nil
  782. case int32:
  783. return strconv.Itoa(int(s)), nil
  784. case int16:
  785. return strconv.FormatInt(int64(s), 10), nil
  786. case int8:
  787. return strconv.FormatInt(int64(s), 10), nil
  788. case uint:
  789. return strconv.FormatInt(int64(s), 10), nil
  790. case uint64:
  791. return strconv.FormatInt(int64(s), 10), nil
  792. case uint32:
  793. return strconv.FormatInt(int64(s), 10), nil
  794. case uint16:
  795. return strconv.FormatInt(int64(s), 10), nil
  796. case uint8:
  797. return strconv.FormatInt(int64(s), 10), nil
  798. case []byte:
  799. return string(s), nil
  800. case template.HTML:
  801. return string(s), nil
  802. case template.URL:
  803. return string(s), nil
  804. case template.JS:
  805. return string(s), nil
  806. case template.CSS:
  807. return string(s), nil
  808. case template.HTMLAttr:
  809. return string(s), nil
  810. case nil:
  811. return "", nil
  812. case fmt.Stringer:
  813. return s.String(), nil
  814. case error:
  815. return s.Error(), nil
  816. default:
  817. return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i)
  818. }
  819. }
  820. // ToStringMapStringE casts an interface to a map[string]string type.
  821. func ToStringMapStringE(i interface{}) (map[string]string, error) {
  822. var m = map[string]string{}
  823. switch v := i.(type) {
  824. case map[string]string:
  825. return v, nil
  826. case map[string]interface{}:
  827. for k, val := range v {
  828. m[ToString(k)] = ToString(val)
  829. }
  830. return m, nil
  831. case map[interface{}]string:
  832. for k, val := range v {
  833. m[ToString(k)] = ToString(val)
  834. }
  835. return m, nil
  836. case map[interface{}]interface{}:
  837. for k, val := range v {
  838. m[ToString(k)] = ToString(val)
  839. }
  840. return m, nil
  841. case string:
  842. err := jsonStringToObject(v, &m)
  843. return m, err
  844. default:
  845. return m, fmt.Errorf("unable to cast %#v of type %T to map[string]string", i, i)
  846. }
  847. }
  848. // ToStringMapStringSliceE casts an interface to a map[string][]string type.
  849. func ToStringMapStringSliceE(i interface{}) (map[string][]string, error) {
  850. var m = map[string][]string{}
  851. switch v := i.(type) {
  852. case map[string][]string:
  853. return v, nil
  854. case map[string][]interface{}:
  855. for k, val := range v {
  856. m[ToString(k)] = ToStringSlice(val)
  857. }
  858. return m, nil
  859. case map[string]string:
  860. for k, val := range v {
  861. m[ToString(k)] = []string{val}
  862. }
  863. case map[string]interface{}:
  864. for k, val := range v {
  865. switch vt := val.(type) {
  866. case []interface{}:
  867. m[ToString(k)] = ToStringSlice(vt)
  868. case []string:
  869. m[ToString(k)] = vt
  870. default:
  871. m[ToString(k)] = []string{ToString(val)}
  872. }
  873. }
  874. return m, nil
  875. case map[interface{}][]string:
  876. for k, val := range v {
  877. m[ToString(k)] = ToStringSlice(val)
  878. }
  879. return m, nil
  880. case map[interface{}]string:
  881. for k, val := range v {
  882. m[ToString(k)] = ToStringSlice(val)
  883. }
  884. return m, nil
  885. case map[interface{}][]interface{}:
  886. for k, val := range v {
  887. m[ToString(k)] = ToStringSlice(val)
  888. }
  889. return m, nil
  890. case map[interface{}]interface{}:
  891. for k, val := range v {
  892. key, err := ToStringE(k)
  893. if err != nil {
  894. return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
  895. }
  896. value, err := ToStringSliceE(val)
  897. if err != nil {
  898. return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
  899. }
  900. m[key] = value
  901. }
  902. case string:
  903. err := jsonStringToObject(v, &m)
  904. return m, err
  905. default:
  906. return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
  907. }
  908. return m, nil
  909. }
  910. // ToStringMapBoolE casts an interface to a map[string]bool type.
  911. func ToStringMapBoolE(i interface{}) (map[string]bool, error) {
  912. var m = map[string]bool{}
  913. switch v := i.(type) {
  914. case map[interface{}]interface{}:
  915. for k, val := range v {
  916. m[ToString(k)] = ToBool(val)
  917. }
  918. return m, nil
  919. case map[string]interface{}:
  920. for k, val := range v {
  921. m[ToString(k)] = ToBool(val)
  922. }
  923. return m, nil
  924. case map[string]bool:
  925. return v, nil
  926. case string:
  927. err := jsonStringToObject(v, &m)
  928. return m, err
  929. default:
  930. return m, fmt.Errorf("unable to cast %#v of type %T to map[string]bool", i, i)
  931. }
  932. }
  933. // ToStringMapE casts an interface to a map[string]interface{} type.
  934. func ToStringMapE(i interface{}) (map[string]interface{}, error) {
  935. var m = map[string]interface{}{}
  936. switch v := i.(type) {
  937. case map[interface{}]interface{}:
  938. for k, val := range v {
  939. m[ToString(k)] = val
  940. }
  941. return m, nil
  942. case map[string]interface{}:
  943. return v, nil
  944. case string:
  945. err := jsonStringToObject(v, &m)
  946. return m, err
  947. default:
  948. return m, fmt.Errorf("unable to cast %#v of type %T to map[string]interface{}", i, i)
  949. }
  950. }
  951. // ToStringMapIntE casts an interface to a map[string]int{} type.
  952. func ToStringMapIntE(i interface{}) (map[string]int, error) {
  953. var m = map[string]int{}
  954. if i == nil {
  955. return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int", i, i)
  956. }
  957. switch v := i.(type) {
  958. case map[interface{}]interface{}:
  959. for k, val := range v {
  960. m[ToString(k)] = ToInt(val)
  961. }
  962. return m, nil
  963. case map[string]interface{}:
  964. for k, val := range v {
  965. m[k] = ToInt(val)
  966. }
  967. return m, nil
  968. case map[string]int:
  969. return v, nil
  970. case string:
  971. err := jsonStringToObject(v, &m)
  972. return m, err
  973. }
  974. if reflect.TypeOf(i).Kind() != reflect.Map {
  975. return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int", i, i)
  976. }
  977. mVal := reflect.ValueOf(m)
  978. v := reflect.ValueOf(i)
  979. for _, keyVal := range v.MapKeys() {
  980. val, err := ToIntE(v.MapIndex(keyVal).Interface())
  981. if err != nil {
  982. return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int", i, i)
  983. }
  984. mVal.SetMapIndex(keyVal, reflect.ValueOf(val))
  985. }
  986. return m, nil
  987. }
  988. // ToStringMapInt64E casts an interface to a map[string]int64{} type.
  989. func ToStringMapInt64E(i interface{}) (map[string]int64, error) {
  990. var m = map[string]int64{}
  991. if i == nil {
  992. return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int64", i, i)
  993. }
  994. switch v := i.(type) {
  995. case map[interface{}]interface{}:
  996. for k, val := range v {
  997. m[ToString(k)] = ToInt64(val)
  998. }
  999. return m, nil
  1000. case map[string]interface{}:
  1001. for k, val := range v {
  1002. m[k] = ToInt64(val)
  1003. }
  1004. return m, nil
  1005. case map[string]int64:
  1006. return v, nil
  1007. case string:
  1008. err := jsonStringToObject(v, &m)
  1009. return m, err
  1010. }
  1011. if reflect.TypeOf(i).Kind() != reflect.Map {
  1012. return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int64", i, i)
  1013. }
  1014. mVal := reflect.ValueOf(m)
  1015. v := reflect.ValueOf(i)
  1016. for _, keyVal := range v.MapKeys() {
  1017. val, err := ToInt64E(v.MapIndex(keyVal).Interface())
  1018. if err != nil {
  1019. return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int64", i, i)
  1020. }
  1021. mVal.SetMapIndex(keyVal, reflect.ValueOf(val))
  1022. }
  1023. return m, nil
  1024. }
  1025. // ToSliceE casts an interface to a []interface{} type.
  1026. func ToSliceE(i interface{}) ([]interface{}, error) {
  1027. var s []interface{}
  1028. switch v := i.(type) {
  1029. case []interface{}:
  1030. return append(s, v...), nil
  1031. case []map[string]interface{}:
  1032. for _, u := range v {
  1033. s = append(s, u)
  1034. }
  1035. return s, nil
  1036. default:
  1037. return s, fmt.Errorf("unable to cast %#v of type %T to []interface{}", i, i)
  1038. }
  1039. }
  1040. // ToBoolSliceE casts an interface to a []bool type.
  1041. func ToBoolSliceE(i interface{}) ([]bool, error) {
  1042. if i == nil {
  1043. return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
  1044. }
  1045. switch v := i.(type) {
  1046. case []bool:
  1047. return v, nil
  1048. }
  1049. kind := reflect.TypeOf(i).Kind()
  1050. switch kind {
  1051. case reflect.Slice, reflect.Array:
  1052. s := reflect.ValueOf(i)
  1053. a := make([]bool, s.Len())
  1054. for j := 0; j < s.Len(); j++ {
  1055. val, err := ToBoolE(s.Index(j).Interface())
  1056. if err != nil {
  1057. return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
  1058. }
  1059. a[j] = val
  1060. }
  1061. return a, nil
  1062. default:
  1063. return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
  1064. }
  1065. }
  1066. // ToStringSliceE casts an interface to a []string type.
  1067. func ToStringSliceE(i interface{}) ([]string, error) {
  1068. var a []string
  1069. switch v := i.(type) {
  1070. case []interface{}:
  1071. for _, u := range v {
  1072. a = append(a, ToString(u))
  1073. }
  1074. return a, nil
  1075. case []string:
  1076. return v, nil
  1077. case string:
  1078. return strings.Fields(v), nil
  1079. case interface{}:
  1080. str, err := ToStringE(v)
  1081. if err != nil {
  1082. return a, fmt.Errorf("unable to cast %#v of type %T to []string", i, i)
  1083. }
  1084. return []string{str}, nil
  1085. default:
  1086. return a, fmt.Errorf("unable to cast %#v of type %T to []string", i, i)
  1087. }
  1088. }
  1089. // ToIntSliceE casts an interface to a []int type.
  1090. func ToIntSliceE(i interface{}) ([]int, error) {
  1091. if i == nil {
  1092. return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
  1093. }
  1094. switch v := i.(type) {
  1095. case []int:
  1096. return v, nil
  1097. }
  1098. kind := reflect.TypeOf(i).Kind()
  1099. switch kind {
  1100. case reflect.Slice, reflect.Array:
  1101. s := reflect.ValueOf(i)
  1102. a := make([]int, s.Len())
  1103. for j := 0; j < s.Len(); j++ {
  1104. val, err := ToIntE(s.Index(j).Interface())
  1105. if err != nil {
  1106. return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
  1107. }
  1108. a[j] = val
  1109. }
  1110. return a, nil
  1111. default:
  1112. return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
  1113. }
  1114. }
  1115. // ToDurationSliceE casts an interface to a []time.Duration type.
  1116. func ToDurationSliceE(i interface{}) ([]time.Duration, error) {
  1117. if i == nil {
  1118. return []time.Duration{}, fmt.Errorf("unable to cast %#v of type %T to []time.Duration", i, i)
  1119. }
  1120. switch v := i.(type) {
  1121. case []time.Duration:
  1122. return v, nil
  1123. }
  1124. kind := reflect.TypeOf(i).Kind()
  1125. switch kind {
  1126. case reflect.Slice, reflect.Array:
  1127. s := reflect.ValueOf(i)
  1128. a := make([]time.Duration, s.Len())
  1129. for j := 0; j < s.Len(); j++ {
  1130. val, err := ToDurationE(s.Index(j).Interface())
  1131. if err != nil {
  1132. return []time.Duration{}, fmt.Errorf("unable to cast %#v of type %T to []time.Duration", i, i)
  1133. }
  1134. a[j] = val
  1135. }
  1136. return a, nil
  1137. default:
  1138. return []time.Duration{}, fmt.Errorf("unable to cast %#v of type %T to []time.Duration", i, i)
  1139. }
  1140. }
  1141. // StringToDate attempts to parse a string into a time.Time type using a
  1142. // predefined list of formats. If no suitable format is found, an error is
  1143. // returned.
  1144. func StringToDate(s string) (time.Time, error) {
  1145. return parseDateWith(s, nil, timeFormats)
  1146. }
  1147. // StringToDateInDefaultLocation to parse a string into a time.Time type using a
  1148. // predefined list of formats, interpreting inputs without a timezone to be in
  1149. // the given location.
  1150. // To fall back to the local timezone, use time.Local as the last argument.
  1151. func StringToDateInDefaultLocation(s string, location *time.Location) (time.Time, error) {
  1152. return parseDateWith(s, location, timeFormats)
  1153. }
  1154. func parseDateWith(s string, location *time.Location, formats []timeFormat) (d time.Time, e error) {
  1155. for _, format := range formats {
  1156. if d, e = time.Parse(format.format, s); e == nil {
  1157. // Some time formats have a zone name, but no offset, so it gets
  1158. // put in that zone name (not the default one passed in to us), but
  1159. // without that zone's offset. So set the location manually.
  1160. // Note that we only do this when we get a location in the new *InDefaultLocation
  1161. // variants to avoid breaking existing behaviour in ToTime, however
  1162. // weird that existing behaviour may be.
  1163. if location != nil && !format.hasNumericTimezone() {
  1164. year, month, day := d.Date()
  1165. hour, min, sec := d.Clock()
  1166. d = time.Date(year, month, day, hour, min, sec, d.Nanosecond(), location)
  1167. }
  1168. return
  1169. }
  1170. }
  1171. return d, fmt.Errorf("unable to parse date: %s", s)
  1172. }
  1173. type timeFormatType int
  1174. const (
  1175. timeFormatShort timeFormatType = iota // time or date only, no timezone
  1176. timeFormatNoTimezone
  1177. // All below have some kind of timezone information, a name and/or offset.
  1178. timeFormatNamedTimezone
  1179. // All below have what we consider to be solid timezone information.
  1180. timeFormatNumericAndNamedTimezone
  1181. timeFormatNumericTimezone
  1182. )
  1183. type timeFormat struct {
  1184. format string
  1185. typ timeFormatType
  1186. }
  1187. func (f timeFormat) hasNumericTimezone() bool {
  1188. return f.typ >= timeFormatNumericAndNamedTimezone
  1189. }
  1190. func (f timeFormat) hasAnyTimezone() bool {
  1191. return f.typ >= timeFormatNamedTimezone
  1192. }
  1193. var (
  1194. timeFormats = []timeFormat{
  1195. {time.RFC3339, timeFormatNumericTimezone},
  1196. {"2006-01-02T15:04:05", timeFormatNoTimezone}, // iso8601 without timezone
  1197. {time.RFC1123Z, timeFormatNumericTimezone},
  1198. {time.RFC1123, timeFormatNamedTimezone},
  1199. {time.RFC822Z, timeFormatNumericTimezone},
  1200. {time.RFC822, timeFormatNamedTimezone},
  1201. {time.RFC850, timeFormatNamedTimezone},
  1202. {"2006-01-02 15:04:05.999999999 -0700 MST", timeFormatNumericAndNamedTimezone}, // Time.String()
  1203. {"2006-01-02T15:04:05-0700", timeFormatNumericTimezone}, // RFC3339 without timezone hh:mm colon
  1204. {"2006-01-02 15:04:05Z0700", timeFormatNumericTimezone}, // RFC3339 without T or timezone hh:mm colon
  1205. {"2006-01-02 15:04:05", timeFormatNoTimezone},
  1206. {time.ANSIC, timeFormatNoTimezone},
  1207. // Must try RubyDate before UnixDate, see:
  1208. // https://github.com/golang/go/issues/32358
  1209. {time.RubyDate, timeFormatNumericTimezone},
  1210. {time.UnixDate, timeFormatNamedTimezone},
  1211. {"2006-01-02 15:04:05Z07:00", timeFormatNumericTimezone},
  1212. {"2006-01-02", timeFormatShort},
  1213. {"02 Jan 2006", timeFormatShort},
  1214. {"2006-01-02 15:04:05 -07:00", timeFormatNumericTimezone},
  1215. {"2006-01-02 15:04:05 -0700", timeFormatNumericTimezone},
  1216. {time.Kitchen, timeFormatShort},
  1217. {time.Stamp, timeFormatShort},
  1218. {time.StampMilli, timeFormatShort},
  1219. {time.StampMicro, timeFormatShort},
  1220. {time.StampNano, timeFormatShort},
  1221. }
  1222. )
  1223. // jsonStringToObject attempts to unmarshall a string as JSON into
  1224. // the object passed as pointer.
  1225. func jsonStringToObject(s string, v interface{}) error {
  1226. data := []byte(s)
  1227. return json.Unmarshal(data, v)
  1228. }