4
4
"bytes"
5
5
"encoding/json"
6
6
"errors"
7
+ "fmt"
7
8
"net/http"
8
9
"net/url"
9
10
"strings"
@@ -13,7 +14,7 @@ type boolean bool
13
14
14
15
// Client represent the wrapper for ipdata.co
15
16
type Client struct {
16
- baseURL * url. URL
17
+ baseURL string
17
18
httpClient * http.Client
18
19
UserAgent string
19
20
APIKey string
@@ -93,21 +94,20 @@ func NewClient(httpClient *http.Client) (*Client, error) {
93
94
httpClient = http .DefaultClient
94
95
}
95
96
96
- baseURL , err := url .Parse ("https://api.ipdata.co" )
97
- if err != nil {
98
- return nil , err
99
- }
100
-
101
97
client := & Client {
102
- baseURL : baseURL ,
98
+ baseURL : "https://api.ipdata.co" ,
103
99
httpClient : httpClient ,
104
100
}
105
101
return client , nil
106
102
}
107
103
108
104
func (c * Client ) newRequest (method , path string ) (* http.Request , error ) {
109
- rel := & url.URL {Path : path }
110
- u := c .baseURL .ResolveReference (rel )
105
+ params := url.Values {}
106
+ params .Add ("api-key" , c .APIKey )
107
+
108
+ u , _ := url .ParseRequestURI (c .baseURL )
109
+ u .Path = path
110
+ u .RawQuery = params .Encode ()
111
111
112
112
req , err := http .NewRequest (method , u .String (), nil )
113
113
if err != nil {
@@ -117,7 +117,6 @@ func (c *Client) newRequest(method, path string) (*http.Request, error) {
117
117
req .Header .Set ("Content-Type" , "application/json" )
118
118
req .Header .Set ("Accept" , "application/json" )
119
119
req .Header .Set ("User-Agent" , c .UserAgent )
120
- req .Header .Set ("Api-Key" , c .APIKey )
121
120
122
121
return req , nil
123
122
}
@@ -150,17 +149,17 @@ func (c *Client) GetIPData(ip string) (*Data, error) {
150
149
resp , body , err := c .do (req , data )
151
150
if err != nil || resp .StatusCode != 200 {
152
151
var errorResponse = & Error {}
153
- json .Unmarshal ([]byte (* body ), errorResponse )
152
+ _ = json .Unmarshal ([]byte (* body ), errorResponse )
154
153
155
154
switch resp .StatusCode {
156
155
case 400 : // Bad Request
157
- return nil , errors .New (* body )
158
- case 403 :
159
156
return nil , errors .New (errorResponse .Message )
157
+ case 401 : // Unauthorized
158
+ return nil , errors .New (fmt .Sprintf ("Unauthorized: %v" , errorResponse .Message ))
160
159
case 429 : // Too Many Requests
161
160
return nil , errors .New ("you have exceeded requests limit. See https://ipdata.co" )
162
161
default :
163
- return nil , err
162
+ return nil , errors . New ( fmt . Sprintf ( "Unknown Error: %v" , errorResponse . Message ))
164
163
}
165
164
}
166
165
data .JSON = body
0 commit comments