-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
82 lines (67 loc) · 1.46 KB
/
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
package gosrm
import (
"compress/gzip"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
)
func (c *Client) http(Url *url.URL) (*OSRMResponse, error) {
req := &http.Request{
Method: http.MethodGet,
URL: Url,
Header: http.Header{
"User-Agent": {"GOSRM/" + Version},
"Accept": {"application/json"},
},
}
if c.options.Debug {
fmt.Printf("[GOSRM][URL]: %s\n", Url.String())
}
if c.options.UseGzip {
req.Header.Add("Accept-Encoding", "gzip")
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, NewGOSRMError(Url, err, nil)
}
defer resp.Body.Close()
var reader io.ReadCloser
switch resp.Header.Get("Content-Encoding") {
case "gzip":
reader, err = gzip.NewReader(resp.Body)
if err != nil {
return nil, NewGOSRMError(Url, err, nil)
}
defer reader.Close()
default:
reader = resp.Body
}
raw, err := ioutil.ReadAll(reader)
if err != nil {
return nil, NewGOSRMError(Url, err, &raw)
}
_, err = io.Copy(ioutil.Discard, resp.Body)
if err != nil {
return nil, NewGOSRMError(Url, err, &raw)
}
if c.options.Debug {
fmt.Printf("[GOSRM][RESPONCE]: %s\n", raw)
}
response := &OSRMResponse{}
if err := json.Unmarshal(raw, &response); err != nil {
return nil, NewGOSRMError(Url, err, &raw)
}
if response.Code != CodeOK {
i, ok := RespCode[response.Code]
if !ok {
i = response.Message
}
e := errors.New(i)
return response, NewGOSRMError(Url, e, &raw)
}
return response, nil
}