This repository has been archived by the owner on Aug 16, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httputil.go
77 lines (67 loc) · 1.76 KB
/
httputil.go
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package httputil
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"github.com/pkg/errors"
)
type Request struct {
http.Request
}
func (request Request) Build() *http.Request {
return &request.Request
}
func NewRequest(method, urlStr string, body io.Reader) *Request {
request, e := http.NewRequest(method, urlStr, body)
if e != nil {
panic(e)
}
return &Request{*request}
}
func (request *Request) WithBasicAuth(username, password string) *Request {
request.SetBasicAuth(username, password)
return request
}
func (request *Request) WithHeader(key, value string) *Request {
request.Header.Add(key, value)
return request
}
func NewPutRequest(url string, formFiles map[string]map[string]io.Reader) (*http.Request, error) {
bodyBuf := &bytes.Buffer{}
contentType, e := AddFormFileTo(bodyBuf, formFiles)
if e != nil {
return nil, errors.Wrapf(e, "url=%v", url)
}
request, e := http.NewRequest("PUT", url, bodyBuf)
if e != nil {
return nil, errors.Wrapf(e, "url=%v", url)
}
request.Header.Add("Content-Type", contentType)
return request, nil
}
func AddFormFileTo(body io.Writer, formFiles map[string]map[string]io.Reader) (contentType string, err error) {
multipartWriter := multipart.NewWriter(body)
for name, filenameAndReader := range formFiles {
for filename, reader := range filenameAndReader {
formFileWriter, e := multipartWriter.CreateFormFile(name, filename)
if e != nil {
err = fmt.Errorf("Could not CreateFormFile with name %v and filename %v", name, filename)
return
}
io.Copy(formFileWriter, reader)
}
}
multipartWriter.Close()
contentType = multipartWriter.FormDataContentType()
return
}
func MustParse(rawUrl string) *url.URL {
u, e := url.ParseRequestURI(rawUrl)
if e != nil {
panic(e)
}
return u
}