grim/youtrack-import

Fix inline images. Fixes YI-41
draft
2020-08-18, Gary Kramlich
1e60d209bf11
Fix inline images. Fixes YI-41
package youtrack
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"path/filepath"
)
type Client struct {
client *http.Client
uri string
}
func NewClient(uri, token string) (*Client, error) {
parts, err := url.Parse(uri)
if err != nil {
return nil, err
}
if filepath.Base(parts.Path) != "rest" {
parts.Path = filepath.Join(parts.Path, "rest")
}
return &Client{
client: &http.Client{
Transport: NewTransport(token),
},
uri: parts.String(),
}, nil
}
func (c *Client) checkStatuses(resp *http.Response, expected []int) error {
for _, acceptable := range expected {
if resp.StatusCode == acceptable {
return nil
}
}
fmt.Printf("failed to find an acceptable status code: got %d\n", resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
xmlErr := xmlError{}
if err := xml.NewDecoder(bytes.NewReader(body)).Decode(&xmlErr); err != nil {
return err
}
return fmt.Errorf(xmlErr.Message)
}
func (c *Client) checkStatus(resp *http.Response, expected int) error {
return c.checkStatuses(resp, []int{expected})
}
func (c *Client) request(method, url string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
return c.client.Do(req)
}
func (c *Client) requestContentType(method, url, contentType string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", contentType)
return c.client.Do(req)
}
func (c *Client) xmlRequest(method, url string, body io.Reader) (*http.Response, error) {
return c.requestContentType(method, url, "application/xml", body)
}