fetch.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package appsrv
  15. import (
  16. "encoding/xml"
  17. "io/ioutil"
  18. "net/http"
  19. "github.com/pkg/errors"
  20. "yunion.io/x/jsonutils"
  21. )
  22. func Fetch(req *http.Request) ([]byte, error) {
  23. defer req.Body.Close()
  24. return ioutil.ReadAll(req.Body)
  25. }
  26. func FetchStruct(req *http.Request, v interface{}) error {
  27. b, e := Fetch(req)
  28. if e != nil {
  29. return e
  30. }
  31. if len(b) > 0 {
  32. obj, err := jsonutils.Parse(b)
  33. if err != nil {
  34. return err
  35. }
  36. return obj.Unmarshal(v)
  37. } else {
  38. return nil
  39. }
  40. }
  41. func FetchJSON(req *http.Request) (jsonutils.JSONObject, error) {
  42. b, e := Fetch(req)
  43. if e != nil {
  44. return nil, e
  45. }
  46. if len(b) > 0 {
  47. return jsonutils.Parse(b)
  48. } else {
  49. return nil, nil
  50. }
  51. }
  52. func FetchXml(req *http.Request, target interface{}) error {
  53. b, e := Fetch(req)
  54. if e != nil {
  55. return errors.Wrap(e, "Fetch")
  56. }
  57. if len(b) > 0 {
  58. return xml.Unmarshal(b, target)
  59. } else {
  60. return nil
  61. }
  62. }