Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding a new WithXML method #402

Merged
merged 1 commit into from
May 31, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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