File: requestdata_upload.go

package info (click to toggle)
golang-github-koofr-go-httpclient 0.0~git20190818.e0dc8fd-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 160 kB
  • sloc: makefile: 2
file content (62 lines) | stat: -rw-r--r-- 1,037 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package httpclient

import (
	"io"
	"mime/multipart"
	"net/http"
)

func (req *RequestData) UploadFile(fieldName string, fileName string, reader io.Reader) (err error) {
	return req.UploadFileExtra(fieldName, fileName, reader, nil)
}

func (req *RequestData) UploadFileExtra(fieldName string, fileName string, reader io.Reader, extra map[string]string) (err error) {
	r, w := io.Pipe()

	writer := multipart.NewWriter(w)

	go func() {
		var err error

		defer func() {
			if err == nil {
				w.Close()
			}
		}()

		for k, v := range extra {
			err = writer.WriteField(k, v)

			if err != nil {
				w.CloseWithError(err)
				return
			}
		}

		part, err := writer.CreateFormFile(fieldName, fileName)

		if err != nil {
			w.CloseWithError(err)
			return
		}

		defer writer.Close()

		_, err = io.Copy(part, reader)

		if err != nil {
			w.CloseWithError(err)
			return
		}
	}()

	req.ReqReader = r

	if req.Headers == nil {
		req.Headers = make(http.Header)
	}

	req.Headers.Set("Content-Type", writer.FormDataContentType())

	return
}