-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate_product.go
78 lines (71 loc) · 2.14 KB
/
update_product.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package sendowl
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"golang.org/x/net/context"
)
// UpdateProductRequest is an API representation of an update product request.
type UpdateProductRequest struct {
ProductID `json:"-"` // ProductID of the product to update.
Name string // Name of the product.
Type ProductType // Type of the product.
Price Price // Price of the product.
Attachment io.Reader
Filename string // Filename of the file to attach.
PDFStamping bool
// SelfHostedURL is the url of the file to be issued at download (only
// useable when the product is self hosted).
SelfHostedURL string
}
func (r *UpdateProductRequest) body() (io.Reader, string, error) {
buf := &bytes.Buffer{}
w := multipart.NewWriter(buf)
w.WriteField("product[name]", r.Name)
w.WriteField("product[product_type]", string(r.Type))
w.WriteField("product[price]", r.Price.String())
if r.PDFStamping {
w.WriteField("product[pdf_stamping]", "true")
}
w.WriteField("product[self_hosted_url]", r.SelfHostedURL)
if r.Attachment != nil {
part, err := w.CreateFormFile("product[attachment]", r.Filename)
if err != nil {
return nil, "", err
}
if _, err := io.Copy(part, r.Attachment); err != nil {
return nil, "", err
}
}
if err := w.Close(); err != nil {
return nil, "", err
}
return buf, w.FormDataContentType(), nil
}
// UpdateProductResponse is an API representation of an update product response.
type UpdateProductResponse struct{}
// UpdateProduct uses req to update a product, returning a UpdateProductResponse
// and non-nil error if there was a problem.
func (c Client) UpdateProduct(ctx context.Context, req UpdateProductRequest) (*UpdateProductResponse, error) {
body, ct, err := req.body()
if err != nil {
return nil, err
}
r, err := c.newRequest("PUT", fmt.Sprintf("./products/%s", req.ProductID), body)
if err != nil {
return nil, err
}
r.Header.Set("Content-Type", ct)
var resp UpdateProductResponse
if err := c.do(ctx, r, &resp); err != nil {
if isEOFErr(err) {
return &resp, nil
}
return nil, err
}
return &resp, nil
}
func isEOFErr(err error) bool {
return err.Error() == "EOF"
}