-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
66 lines (54 loc) · 1.36 KB
/
request.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
// Copyright (c) 2020 Pieoneers Software Incorporated. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package client
import (
"bytes"
"github.com/pieoneers/jsonapi-go"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
)
//Request represents the request data
type Request struct {
//HTTP request method
Method string
//Request URL or it may be a path to the resource
URL *url.URL
// Query params
Query url.Values
// Request headers
Header http.Header
// Request body
Body io.ReadCloser
}
// NewRequest return new Request instance with corresponding parameters
func NewRequest(method, rawurl string, in interface{}) (*Request, error) {
url, urlErr := url.ParseRequestURI(rawurl)
if urlErr != nil {
return nil, urlErr
}
req := Request{
Method: method,
URL: url,
Header: make(http.Header),
}
req.Query = req.URL.Query()
req.Header.Add("Accept", jsonapi.ContentType)
if reflect.TypeOf(in) != nil {
req.Header.Add("Content-Type", jsonapi.ContentType)
payload, marshalErr := jsonapi.Marshal(in)
if marshalErr != nil {
return nil, marshalErr
}
req.Body = ioutil.NopCloser(bytes.NewReader(payload))
}
return &req, nil
}
//RequestURI returns request URI
func (req *Request) RequestURI() string {
req.URL.RawQuery = req.Query.Encode()
return req.URL.RequestURI()
}