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.

67 lines
1.6 KiB

12 years ago
  1. package operation
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "mime"
  11. "mime/multipart"
  12. "net/http"
  13. "net/textproto"
  14. "path/filepath"
  15. "strings"
  16. )
  17. type UploadResult struct {
  18. Size int
  19. Error string
  20. }
  21. func Upload(uploadUrl string, filename string, reader io.Reader, isGzipped bool) (*UploadResult, error) {
  22. body_buf := bytes.NewBufferString("")
  23. body_writer := multipart.NewWriter(body_buf)
  24. h := make(textproto.MIMEHeader)
  25. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, filename))
  26. h.Set("Content-Type", mime.TypeByExtension(strings.ToLower(filepath.Ext(filename))))
  27. if isGzipped {
  28. h.Set("Content-Encoding", "gzip")
  29. }
  30. file_writer, err := body_writer.CreatePart(h)
  31. if err != nil {
  32. log.Println("error creating form file", err)
  33. return nil, err
  34. }
  35. if _, err = io.Copy(file_writer, reader); err != nil {
  36. log.Println("error copying data", err)
  37. return nil, err
  38. }
  39. content_type := body_writer.FormDataContentType()
  40. if err = body_writer.Close(); err != nil {
  41. log.Println("error closing body", err)
  42. return nil, err
  43. }
  44. resp, err := http.Post(uploadUrl, content_type, body_buf)
  45. if err != nil {
  46. log.Println("failing to upload to", uploadUrl)
  47. return nil, err
  48. }
  49. defer resp.Body.Close()
  50. resp_body, err := ioutil.ReadAll(resp.Body)
  51. if err != nil {
  52. return nil, err
  53. }
  54. var ret UploadResult
  55. err = json.Unmarshal(resp_body, &ret)
  56. if err != nil {
  57. log.Println("failing to read upload resonse", uploadUrl, resp_body)
  58. return nil, err
  59. }
  60. if ret.Error != "" {
  61. return nil, errors.New(ret.Error)
  62. }
  63. return &ret, nil
  64. }