-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrestful.go
More file actions
212 lines (167 loc) · 5.14 KB
/
restful.go
File metadata and controls
212 lines (167 loc) · 5.14 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package restful
import (
"bytes"
"crypto/rand"
"crypto/tls"
"encoding/base64"
"fmt"
"http"
"io"
"log"
"net"
"os"
"strings"
"time"
)
type readCloser struct {
io.Reader
io.Closer
}
type closer struct {
io.Reader
}
func (closer) Close() os.Error { return nil }
type RestClient struct {
Endpoint string
Proxy string
UserInfo string
// TODO(devcamcar): UserAgent string
}
func (client *RestClient) SubmitRequest(url, method string, headers, params map[string]string) (*http.Response, os.Error) {
var request *http.Request
var response *http.Response
var body string
var err os.Error
if headers == nil {
headers = make(map[string]string)
headers["Content-Type"] = "text/plain"
}
method = strings.ToUpper(method)
rawurl := strings.Join([]string { client.Endpoint, url }, "")
if params != nil {
if method == "GET" {
rawurl += "?" + urlEncode(¶ms)
} else if method == "PUT" || method == "POST" {
headers["Content-Type"] = "application/x-www-form-urlencoded"
body = urlEncode(¶ms)
}
}
log.Stdout("URL: " + rawurl)
log.Stdout("Body: " + body)
if len(client.UserInfo) > 0 {
enc := base64.URLEncoding
encoded := make([]byte, enc.EncodedLen(len(client.UserInfo)))
enc.Encode(encoded, []byte(client.UserInfo))
headers["Authorization"] = "Basic " + string(encoded)
}
if request, err = prepareHttpRequest(rawurl, method, &headers); err != nil {
return nil, err
}
if len(body) > 0 {
request.ContentLength = int64(len(body))
request.Body = closer{bytes.NewBufferString(body)}
}
dump, _ := http.DumpRequest(request, true)
log.Stdout(string(dump))
if response, err = client.sendHttpRequest(request); err != nil {
return nil, err
}
return response, nil
}
func urlEncode(data *map[string]string) string {
args := ""
for key, value := range *data {
if len(args) > 0 {
args += "&"
}
args += fmt.Sprintf("%s=%s", key, value)
}
return args
}
func prepareHttpRequest(rawurl, method string, headers *map[string]string) (*http.Request, os.Error) {
var request http.Request
var url *http.URL
var err os.Error
if url, err = http.ParseURL(rawurl); err != nil {
return nil, err
}
request.Header = *headers
request.Method = method
request.URL = url
return &request, nil
}
func (client *RestClient) sendHttpRequest(req *http.Request) (resp *http.Response, err os.Error) {
var conn *http.ClientConn;
if conn, err = makeConnection(req.URL, client.Proxy); err != nil {
return nil, err
}
err = conn.Write(req)
if protoerr, ok := err.(*http.ProtocolError); ok && protoerr == http.ErrPersistEOF {
// the connection has been closed in an HTTP keepalive sense
conn, _ = makeConnection(req.URL, client.Proxy)
err = conn.Write(req)
} else if err == io.ErrUnexpectedEOF {
// the underlying connection has been closed "gracefully"
conn, _ = makeConnection(req.URL, client.Proxy)
err = conn.Write(req)
}
if err != nil {
return nil, err
}
resp, err = conn.Read()
if protoerr, ok := err.(*http.ProtocolError); ok && protoerr == http.ErrPersistEOF {
// the remote requested that this be the last request serviced
conn, _ = makeConnection(req.URL, client.Proxy)
} else if err != nil {
return nil, err
}
log.Stdout(resp.Proto + " " + resp.Status);
if len(resp.Header) > 0 {
for key, val := range resp.Header {
fmt.Println("\x1b[1m" + key + "\x1b[22m: " + val)
}
fmt.Println()
}
return
}
func makeConnection(url *http.URL, proxy string) (*http.ClientConn, os.Error) {
var tcp net.Conn
var useSSL bool
var conn *http.ClientConn
var err os.Error
// Determine host and port.
addr := url.Host;
if !hasPort(addr) {
if url.Scheme == "https" {
useSSL = true
addr += ":443"
} else {
addr += ":80"
}
}
if len(proxy) > 0 {
proxy_url, _ := http.ParseURL(proxy)
tcp, err = net.Dial("tcp", "", proxy_url.Host)
} else {
tcp, err = net.Dial("tcp", "", addr)
}
if err != nil {
return nil, err
}
if useSSL {
cf := &tls.Config{Rand: rand.Reader, Time: time.Nanoseconds}
ssl := tls.Client(tcp, cf)
conn = http.NewClientConn(ssl, nil)
if len(proxy) > 0 {
tcp.Write([]byte("CONNECT " + addr + " HTTP/1.0\r\n\r\n"))
b := make([]byte, 1024)
tcp.Read(b)
}
} else {
conn = http.NewClientConn(tcp, nil)
}
return conn, nil
}
// Given a string of the form "host", "host:port", or "[ipv6::address]:port",
// return true if the string includes a port.
func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") }