-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
100 lines (93 loc) · 2.61 KB
/
user.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
package zoomeye
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
)
// this func will generate a request, add JWT http header and check http statu code
func (u *User) BuildApiReq(method string, path string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(method, ApiUrl+path, body)
if err != nil {
return &http.Response{}, err
}
u.setJWTHead(req)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return &http.Response{}, err
}
err = u.CheckApiError(resp)
if err != nil {
return &http.Response{}, err
}
return resp, nil
}
// set JWT http head. like `Authorization: JWT token"`
func (u *User) setJWTHead(req *http.Request) {
head := fmt.Sprintf(JWTHead, u.AccessToken)
req.Header.Set("Authorization", head)
}
// check request status
func (u *User) CheckApiError(resp *http.Response) error {
if resp.StatusCode == 200 {
return nil
}
body, _ := ioutil.ReadAll(resp.Body)
apiError := ApiError{}
err := json.Unmarshal(body, apiError)
if err != nil {
return errors.New("错误: http code" + string(resp.StatusCode))
}
return errors.New(apiError.Message + " " + apiError.Url)
}
// get account search resource info
func (u *User) ResourcesInfo() (ResourcesInfo, error) {
resp, err := u.BuildApiReq("GET", ResourcesApiPath, nil)
if err != nil {
return ResourcesInfo{}, err
}
body, _ := ioutil.ReadAll(resp.Body)
resources := ResourcesInfo{}
err = json.Unmarshal(body, &resources)
if err != nil {
return ResourcesInfo{}, err
}
return resources, nil
}
// zoomeye host search
// query string nend url encode
// facets allow value in "github.com/Earth-Online/zoomeye-api/facets"
// page is search page num
func (u *User) HostSearch(query string, page int, facets []string) (ret HostSearchInfo, err error) {
fStr := "%s?query=%s&page=%d&facets=%s"
url := fmt.Sprintf(fStr, HostSearchApiPath, query, page, strings.Join(facets, ","))
resp, err := u.BuildApiReq("GET", url, nil)
if err != nil {
return
}
body, _ := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(body, &ret)
return
}
// zoomeye web search
// query string nend url encode
// facets allow value in "github.com/Earth-Online/zoomeye-api/facets"
// page is search page num
func (u *User) WebSearch(query string, page int, facets []string) (ret WebSearchInfo, err error) {
fStr := "%s?query=%s&page=%d&facets=%s"
url := fmt.Sprintf(fStr, WebSearchApiPath, query, page, strings.Join(facets, ","))
resp, err := u.BuildApiReq("GET", url, nil)
if err != nil {
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
err = json.Unmarshal(body, &ret)
return
}