另客网go项目公用的代码库

xml.go 701B

12345678910111213141516171819202122232425262728293031323334
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package binding
  5. import (
  6. "bytes"
  7. "encoding/xml"
  8. "io"
  9. "net/http"
  10. )
  11. type xmlBinding struct{}
  12. func (xmlBinding) Name() string {
  13. return "xml"
  14. }
  15. func (xmlBinding) Bind(req *http.Request, obj interface{}) error {
  16. return decodeXML(req.Body, obj)
  17. }
  18. func (xmlBinding) BindBody(body []byte, obj interface{}) error {
  19. return decodeXML(bytes.NewReader(body), obj)
  20. }
  21. func decodeXML(r io.Reader, obj interface{}) error {
  22. decoder := xml.NewDecoder(r)
  23. if err := decoder.Decode(obj); err != nil {
  24. return err
  25. }
  26. return validate(obj)
  27. }