...
1 package httpx
2
3 import (
4 "bytes"
5 "encoding/json"
6 "io"
7 "net/http"
8 "net/url"
9 "strings"
10
11 "github.com/pkg/errors"
12 )
13
14
15 func NewRequestJSON(method, url string, data interface{}) (*http.Request, error) {
16 var b bytes.Buffer
17 if err := json.NewEncoder(&b).Encode(data); err != nil {
18 return nil, errors.WithStack(err)
19 }
20 req, err := http.NewRequest(method, url, &b)
21 if err != nil {
22 return nil, errors.WithStack(err)
23 }
24 req.Header.Set("Content-Type", "application/json")
25 return req, nil
26 }
27
28
29 func NewRequestForm(method, url string, data url.Values) (*http.Request, error) {
30 req, err := http.NewRequest(method, url, strings.NewReader(data.Encode()))
31 if err != nil {
32 return nil, errors.WithStack(err)
33 }
34 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
35 return req, nil
36 }
37
38
39 func MustNewRequest(method, url string, body io.Reader, contentType string) *http.Request {
40 req, err := http.NewRequest(method, url, body)
41 if err != nil {
42 panic(err)
43 }
44 if contentType != "" {
45 req.Header.Set("Content-Type", contentType)
46 }
47 return req
48 }
49
View as plain text