-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
115 lines (89 loc) · 2.14 KB
/
client.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package growi_client
import (
"encoding/json"
"github.com/ictsc/growi_client/entity"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
)
type Client interface {
GetSubordinatedPage(path string) ([]entity.SubordinatedPage, error)
GetPage(path string) (*entity.Page, error)
}
type GrowiClientOption struct {
URL *url.URL
AccessToken string
}
type GrowiClient struct {
Jar *cookiejar.Jar
Option *GrowiClientOption
}
var client *http.Client
var _ Client = (*GrowiClient)(nil)
func NewGrowiClient(option *GrowiClientOption) *GrowiClient {
client = &http.Client{}
return &GrowiClient{
Option: option,
}
}
type SubordinatedPagesResponse struct {
SubordinatedPages []entity.SubordinatedPage `json:"subordinatedPages"`
}
func (c *GrowiClient) GetSubordinatedPage(path string) ([]entity.SubordinatedPage, error) {
u := *c.Option.URL
u.Path = "_api/v3/pages/subordinated-list"
q := u.Query()
q.Set("access_token", c.Option.AccessToken)
q.Set("path", path)
u.RawQuery = q.Encode()
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var subordinatedPagesResponse SubordinatedPagesResponse
err = json.Unmarshal(body, &subordinatedPagesResponse)
if err != nil {
return nil, err
}
return subordinatedPagesResponse.SubordinatedPages, nil
}
type PageResponse struct {
Page entity.Page `json:"page"`
}
func (c *GrowiClient) GetPage(path string) (*entity.Page, error) {
u := *c.Option.URL
u.Path = "_api/v3/page"
q := u.Query()
q.Set("access_token", c.Option.AccessToken)
q.Set("path", path)
u.RawQuery = q.Encode()
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var pageResponse PageResponse
err = json.Unmarshal(body, &pageResponse)
if err != nil {
return nil, err
}
return &pageResponse.Page, nil
}