Commit 1a2af71a authored by Sander van Harmelen's avatar Sander van Harmelen

Refactor the `UploadFile` function

parent 7d5edaf7
......@@ -22,7 +22,6 @@ import (
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"os"
"time"
......@@ -807,61 +806,55 @@ func (s *ProjectsService) DeleteProjectForkRelation(pid int, options ...OptionFu
return s.client.Do(req, nil)
}
// ProjectFile upload a file
// ProjectFile represents an uploaded project file
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/projects.html#upload-a-file
// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#upload-a-file
type ProjectFile struct {
Alt string `json:"alt"`
URL string `json:"url"`
Markdown string `json:"markdown"`
}
// UploadFile upload a file
// UploadFile upload a file from disk
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/projects.html#upload-a-file
func (s *ProjectsService) UploadFile(pid interface{}, file string) (*ProjectFile, *Response, error) {
// GitLab API docs: https://docs.gitlab.com/ce/api/projects.html#upload-a-file
func (s *ProjectsService) UploadFile(pid interface{}, file string, options ...OptionFunc) (*ProjectFile, *Response, error) {
project, err := parseID(pid)
if err != nil {
return nil, nil, err
}
u := fmt.Sprintf("projects/%s/uploads", url.QueryEscape(project))
options := []OptionFunc{func(req *http.Request) error {
req.Method = http.MethodPost
b := &bytes.Buffer{}
w := multipart.NewWriter(b)
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
fw, err := w.CreateFormFile("file", file)
if err != nil {
return err
}
_, err = io.Copy(fw, f)
if err != nil {
return err
}
w.Close()
f, err := os.Open(file)
if err != nil {
return nil, nil, err
}
defer f.Close()
req.Body = ioutil.NopCloser(b)
req.ContentLength = int64(b.Len())
b := &bytes.Buffer{}
w := multipart.NewWriter(b)
req.Header.Set("Content-Type", w.FormDataContentType())
fw, err := w.CreateFormFile("file", file)
if err != nil {
return nil, nil, err
}
return nil
}}
_, err = io.Copy(fw, f)
if err != nil {
return nil, nil, err
}
w.Close()
req, err := s.client.NewRequest("", u, nil, options)
if err != nil {
return nil, nil, err
}
req.Body = ioutil.NopCloser(b)
req.ContentLength = int64(b.Len())
req.Header.Set("Content-Type", w.FormDataContentType())
req.Method = "POST"
uf := &ProjectFile{}
resp, err := s.client.Do(req, uf)
if err != nil {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment