You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.0 KiB

  1. package operation
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. _ "fmt"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "mime/multipart"
  11. "net/http"
  12. )
  13. type UploadResult struct {
  14. Size int
  15. Error string
  16. }
  17. func Upload(uploadUrl string, filename string, reader io.Reader) (*UploadResult, error) {
  18. body_buf := bytes.NewBufferString("")
  19. body_writer := multipart.NewWriter(body_buf)
  20. file_writer, err := body_writer.CreateFormFile("file", filename)
  21. io.Copy(file_writer, reader)
  22. content_type := body_writer.FormDataContentType()
  23. body_writer.Close()
  24. resp, err := http.Post(uploadUrl, content_type, body_buf)
  25. if err != nil {
  26. log.Println("failing to upload to", uploadUrl)
  27. return nil, err
  28. }
  29. defer resp.Body.Close()
  30. resp_body, err := ioutil.ReadAll(resp.Body)
  31. if err != nil {
  32. return nil, err
  33. }
  34. var ret UploadResult
  35. err = json.Unmarshal(resp_body, &ret)
  36. if err != nil {
  37. log.Println("failing to read upload resonse", uploadUrl, resp_body)
  38. return nil, err
  39. }
  40. if ret.Error != "" {
  41. return nil, errors.New(ret.Error)
  42. }
  43. return &ret, nil
  44. }