1
0
Fork 0
mirror of https://github.com/vbatts/imgsrv.git synced 2024-11-24 00:55:41 +00:00
imgsrv/client/client.go

68 lines
1.4 KiB
Go
Raw Normal View History

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")
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 {
return nil, err
2013-05-10 19:03:54 +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 {
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()
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
}
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)
if err != nil {
return "", err
2013-05-10 19:03:54 +00:00
}
client := &http.Client{}
2013-10-10 14:31:27 +00:00
resp, err := client.Do(request)
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 {
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-10-10 14:31:27 +00:00
return string(bytes), nil
}