forked from o1egl/go-wordpress
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdiscovery.go
86 lines (80 loc) · 2.05 KB
/
discovery.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
package wordpress
import (
"context"
"net/http"
"github.com/PuerkitoBio/goquery"
"github.com/tomnomnom/linkheader"
)
// DiscoveredAPI is a struct containing details about a discovered WordPress REST API.
type DiscoveredAPI struct {
BaseURL string
DiscoveredURL string
ViaHeader bool
ViaHTML bool
Client *Client
BasicInfo *RootInfo
}
// DiscoverAPI will discover the API root URL for the given base URL.
func DiscoverAPI(baseURL string, getRootInfo bool) (*DiscoveredAPI, error) {
discovered := &DiscoveredAPI{
BaseURL: baseURL,
}
res, httpErr := http.Get(baseURL)
if httpErr != nil {
return nil, httpErr
}
if res.Header.Get("Link") != "" {
discoveredURL, linkErr := linkHeader(res)
if linkErr != nil {
return nil, linkErr
}
discovered.DiscoveredURL = discoveredURL
discovered.ViaHeader = true
} else {
discoveredURL, linkErr := extractLinkFromHTML(res)
if linkErr != nil {
return nil, linkErr
}
discovered.DiscoveredURL = discoveredURL
discovered.ViaHTML = true
}
if getRootInfo {
client, clientErr := NewClient(discovered.DiscoveredURL, nil)
if clientErr != nil {
return nil, clientErr
}
info, _, basicInfoErr := client.BasicInfo(context.Background())
if basicInfoErr != nil {
return nil, basicInfoErr
}
client.Location = info.Location
discovered.BasicInfo = info
discovered.Client = client
return discovered, nil
}
client, clientErr := NewClient(discovered.DiscoveredURL, nil)
if clientErr != nil {
return nil, clientErr
}
discovered.Client = client
return discovered, nil
}
func linkHeader(resp *http.Response) (string, error) {
for _, link := range linkheader.Parse(resp.Header.Get("Link")) {
if link.Rel == "https://api.w.org/" {
return link.URL, nil
}
}
return "", nil
}
func extractLinkFromHTML(resp *http.Response) (string, error) {
doc, docErr := goquery.NewDocumentFromResponse(resp)
if docErr != nil {
return "", docErr
}
href, hrefExists := doc.Find(`link[rel="https://api.w.org/"]`).Attr("href")
if hrefExists {
return href, nil
}
return "", nil
}