Files
asciinema/api/http.go

94 lines
1.9 KiB
Go
Raw Permalink Normal View History

2014-11-02 19:04:19 +01:00
package api
import (
"bytes"
"io"
"mime/multipart"
"net/http"
"strings"
)
type HTTP interface {
PostForm(string, string, string, map[string]string, map[string]io.ReadCloser) (*http.Response, error)
2014-11-02 19:04:19 +01:00
}
2014-11-15 13:33:20 +01:00
type HTTPClient struct{}
2014-11-02 19:04:19 +01:00
func (c *HTTPClient) PostForm(url, username, password string, headers map[string]string, files map[string]io.ReadCloser) (*http.Response, error) {
req, err := createPostRequest(url, username, password, headers, files)
2014-11-02 19:04:19 +01:00
if err != nil {
return nil, err
}
client := &http.Client{}
return client.Do(req)
}
func createPostRequest(url, username, password string, headers map[string]string, files map[string]io.ReadCloser) (*http.Request, error) {
2015-05-02 10:09:26 +02:00
body, contentType, err := multiPartBody(files)
if err != nil {
return nil, err
}
2014-11-02 19:04:19 +01:00
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
setHeaders(req, contentType, username, password, headers)
return req, nil
}
func setHeaders(req *http.Request, contentType, username, password string, headers map[string]string) {
2014-11-02 19:04:19 +01:00
req.SetBasicAuth(username, password)
req.Header.Set("Content-Type", contentType)
for name, value := range headers {
req.Header.Set(name, value)
}
2014-11-02 19:04:19 +01:00
}
2015-05-02 10:09:26 +02:00
func multiPartBody(files map[string]io.ReadCloser) (io.Reader, string, error) {
2014-11-02 19:04:19 +01:00
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
if files != nil {
for name, file := range files {
err := addFormFile(writer, name, file)
2014-11-02 19:04:19 +01:00
if err != nil {
return nil, "", err
}
file.Close()
2014-11-02 19:04:19 +01:00
}
}
err := writer.Close()
if err != nil {
return nil, "", err
}
return body, writer.FormDataContentType(), nil
}
func addFormFile(writer *multipart.Writer, name string, reader io.Reader) error {
items := strings.Split(name, ":")
fieldname := items[0]
filename := items[1]
part, err := writer.CreateFormFile(fieldname, filename)
if err != nil {
return err
}
_, err = io.Copy(part, reader)
if err != nil {
return err
}
return nil
}