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.

57 lines
1.3 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. if err != nil {
  22. log.Println("error creating form file", err)
  23. return nil, err
  24. }
  25. if _, err = io.Copy(file_writer, reader); err != nil {
  26. log.Println("error copying data", err)
  27. return nil, err
  28. }
  29. content_type := body_writer.FormDataContentType()
  30. if err = body_writer.Close(); err != nil {
  31. log.Println("error closing body", err)
  32. return nil, err
  33. }
  34. resp, err := http.Post(uploadUrl, content_type, body_buf)
  35. if err != nil {
  36. log.Println("failing to upload to", uploadUrl)
  37. return nil, err
  38. }
  39. defer resp.Body.Close()
  40. resp_body, err := ioutil.ReadAll(resp.Body)
  41. if err != nil {
  42. return nil, err
  43. }
  44. var ret UploadResult
  45. err = json.Unmarshal(resp_body, &ret)
  46. if err != nil {
  47. log.Println("failing to read upload resonse", uploadUrl, resp_body)
  48. return nil, err
  49. }
  50. if ret.Error != "" {
  51. return nil, errors.New(ret.Error)
  52. }
  53. return &ret, nil
  54. }