-
Notifications
You must be signed in to change notification settings - Fork 36
/
adapter-http.go
128 lines (106 loc) · 2.49 KB
/
adapter-http.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package ipp
import (
"bytes"
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"strconv"
)
type HttpAdapter struct {
host string
port int
username string
password string
useTLS bool
client *http.Client
}
func NewHttpAdapter(host string, port int, username, password string, useTLS bool) *HttpAdapter {
httpClient := http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
return &HttpAdapter{
host: host,
port: port,
username: username,
password: password,
useTLS: useTLS,
client: &httpClient,
}
}
func (h *HttpAdapter) SendRequest(url string, req *Request, additionalResponseData io.Writer) (*Response, error) {
payload, err := req.Encode()
if err != nil {
return nil, err
}
size := len(payload)
var body io.Reader
if req.File != nil && req.FileSize != -1 {
size += req.FileSize
body = io.MultiReader(bytes.NewBuffer(payload), req.File)
} else {
body = bytes.NewBuffer(payload)
}
httpReq, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
httpReq.Header.Set("Content-Length", strconv.Itoa(size))
httpReq.Header.Set("Content-Type", ContentTypeIPP)
if h.username != "" && h.password != "" {
httpReq.SetBasicAuth(h.username, h.password)
}
httpResp, err := h.client.Do(httpReq)
if err != nil {
return nil, err
}
defer httpResp.Body.Close()
if httpResp.StatusCode != 200 {
return nil, HTTPError{
Code: httpResp.StatusCode,
}
}
// buffer response to avoid read issues
buf := new(bytes.Buffer)
if httpResp.ContentLength > 0 {
buf.Grow(int(httpResp.ContentLength))
}
if _, err := io.Copy(buf, httpResp.Body); err != nil {
return nil, fmt.Errorf("unable to buffer response: %w", err)
}
ippResp, err := NewResponseDecoder(buf).Decode(additionalResponseData)
if err != nil {
return nil, err
}
if err = ippResp.CheckForErrors(); err != nil {
return nil, fmt.Errorf("received error IPP response: %w", err)
}
return ippResp, nil
}
func (h *HttpAdapter) GetHttpUri(namespace string, object interface{}) string {
proto := "http"
if h.useTLS {
proto = "https"
}
uri := fmt.Sprintf("%s://%s:%d", proto, h.host, h.port)
if namespace != "" {
uri = fmt.Sprintf("%s/%s", uri, namespace)
}
if object != nil {
uri = fmt.Sprintf("%s/%v", uri, object)
}
return uri
}
func (h *HttpAdapter) TestConnection() error {
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", h.host, h.port))
if err != nil {
return err
}
conn.Close()
return nil
}