2013-05-10 19:03:54 +00:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
2013-10-10 14:31:27 +00:00
|
|
|
"bytes"
|
|
|
|
"errors"
|
|
|
|
"io"
|
2013-05-10 19:03:54 +00:00
|
|
|
"io/ioutil"
|
2013-10-10 14:31:27 +00:00
|
|
|
"mime/multipart"
|
2013-05-10 19:03:54 +00:00
|
|
|
"net/http"
|
|
|
|
"os"
|
2013-10-10 14:31:27 +00:00
|
|
|
"path"
|
2013-05-10 19:03:54 +00:00
|
|
|
)
|
|
|
|
|
2013-10-10 14:31:27 +00:00
|
|
|
var ErrorNotOK = errors.New("HTTP Response was not 200 OK")
|
|
|
|
|
2013-10-09 21:02:38 +00:00
|
|
|
func NewfileUploadRequest(uri, file_path string, params map[string]string) (*http.Request, error) {
|
|
|
|
file, err := os.Open(file_path)
|
2013-05-10 19:03:54 +00:00
|
|
|
if err != nil {
|
2013-10-09 21:02:38 +00:00
|
|
|
return nil, err
|
2013-05-10 19:03:54 +00:00
|
|
|
}
|
2013-10-09 21:02:38 +00:00
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
body := &bytes.Buffer{}
|
|
|
|
writer := multipart.NewWriter(body)
|
|
|
|
part, err := writer.CreateFormFile("filename", path.Base(file_path))
|
2013-05-10 19:03:54 +00:00
|
|
|
if err != nil {
|
2013-10-09 21:02:38 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
_, err = io.Copy(part, file)
|
|
|
|
|
|
|
|
for key, val := range params {
|
|
|
|
_ = writer.WriteField(key, val)
|
|
|
|
}
|
2013-10-10 14:31:27 +00:00
|
|
|
_ = writer.WriteField("returnUrl", "true")
|
|
|
|
contentType := writer.FormDataContentType()
|
2013-10-09 21:02:38 +00:00
|
|
|
err = writer.Close()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2013-10-10 14:31:27 +00:00
|
|
|
req, err := http.NewRequest("POST", uri, body)
|
|
|
|
req.Header.Add("Content-Type", contentType)
|
|
|
|
return req, err
|
2013-10-09 21:02:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func PutFileFromPath(uri, file_path string, params map[string]string) (path string, err error) {
|
2013-10-10 14:31:27 +00:00
|
|
|
request, err := NewfileUploadRequest(uri, file_path, params)
|
2013-10-09 21:02:38 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
2013-05-10 19:03:54 +00:00
|
|
|
}
|
2013-10-09 21:02:38 +00:00
|
|
|
|
|
|
|
client := &http.Client{}
|
2013-10-10 14:31:27 +00:00
|
|
|
resp, err := client.Do(request)
|
2013-10-09 21:02:38 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2013-10-10 14:31:27 +00:00
|
|
|
defer resp.Body.Close()
|
2013-05-10 19:03:54 +00:00
|
|
|
bytes, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
2013-10-09 21:02:38 +00:00
|
|
|
return "", err
|
2013-05-10 19:03:54 +00:00
|
|
|
}
|
2013-10-10 14:31:27 +00:00
|
|
|
if resp.StatusCode != 200 {
|
|
|
|
return string(bytes), ErrorNotOK
|
2013-08-22 21:29:07 +00:00
|
|
|
}
|
2013-10-10 14:31:27 +00:00
|
|
|
|
|
|
|
return string(bytes), nil
|
2013-08-22 21:29:07 +00:00
|
|
|
}
|