Skip to content

Commit

Permalink
Adding a new WithXML method (#402)
Browse files Browse the repository at this point in the history
  • Loading branch information
tombuildsstuff authored and jhendrixMSFT committed May 31, 2019
1 parent b3989e6 commit 6dadc53
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
23 changes: 23 additions & 0 deletions autorest/preparer.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package autorest
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
Expand Down Expand Up @@ -377,6 +378,28 @@ func WithJSON(v interface{}) PrepareDecorator {
}
}

// WithXML returns a PrepareDecorator that encodes the data passed as XML into the body of the
// request and sets the Content-Length header.
func WithXML(v interface{}) PrepareDecorator {
return func(p Preparer) Preparer {
return PreparerFunc(func(r *http.Request) (*http.Request, error) {
r, err := p.Prepare(r)
if err == nil {
b, err := xml.Marshal(v)
if err == nil {
// we have to tack on an XML header
withHeader := xml.Header + string(b)
bytesWithHeader := []byte(withHeader)

r.ContentLength = int64(len(bytesWithHeader))
r.Body = ioutil.NopCloser(bytes.NewReader(bytesWithHeader))
}
}
return r, err
})
}
}

// WithPath returns a PrepareDecorator that adds the supplied path to the request URL. If the path
// is absolute (that is, it begins with a "/"), it replaces the existing path.
func WithPath(path string) PrepareDecorator {
Expand Down
20 changes: 20 additions & 0 deletions autorest/preparer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,26 @@ func ExampleWithJSON() {
// Output: Request Body contains {"name":"Rob Pike","age":42}
}

// Create a request whose Body is the XML encoding of a structure
func ExampleWithXML() {
t := mocks.T{Name: "Rob Pike", Age: 42}

r, err := Prepare(&http.Request{},
WithXML(&t))
if err != nil {
fmt.Printf("ERROR: %v\n", err)
}

b, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Printf("ERROR: %v\n", err)
} else {
fmt.Printf("Request Body contains %s\n", string(b))
}
// Output: Request Body contains <?xml version="1.0" encoding="UTF-8"?>
// <T><Name>Rob Pike</Name><Age>42</Age></T>
}

// Create a request from a path with escaped parameters
func ExampleWithEscapedPathParameters() {
params := map[string]interface{}{
Expand Down

0 comments on commit 6dadc53

Please sign in to comment.