-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusers_api.go
48 lines (39 loc) · 1002 Bytes
/
users_api.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type UserAPI struct {
Port, URL string
}
func NewUserAPI(url, port string) UserAPI {
return UserAPI{
Port: port,
URL: url,
}
}
func (api UserAPI) Search(term string) (users Users, err error) {
uri := fmt.Sprintf("%s:%s", api.URL, api.Port)
r, err := http.NewRequest(http.MethodGet, uri, nil)
if err != nil {
return nil, fmt.Errorf("UserAPI.Search: error creating request: %v", err)
}
q := r.URL.Query()
q.Add("search", term)
r.URL.RawQuery = q.Encode()
res, err := http.DefaultClient.Do(r)
if err != nil {
return nil, fmt.Errorf("UserAPI.Search: error making request: %v", err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("UserAPI.Search: error reading request body: %v", err)
}
if err := json.Unmarshal(body, &users); err != nil {
return nil, fmt.Errorf("UserAPI.Search: error unmarshaling JSON: %v", err)
}
return users, nil
}