-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwp-api.go
More file actions
103 lines (88 loc) · 2.29 KB
/
wp-api.go
File metadata and controls
103 lines (88 loc) · 2.29 KB
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
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
)
func wpDataFromURL(URL string, numberPerPage int) error {
var i interface{} // empty interface to pass into get default dir
outputDir := directoryFromStruct(i, false)
// check to see if the API output directory exists
_, err := os.Stat(outputDir)
if os.IsNotExist(err) {
// if it doesn't run the get
for _, t := range contentTypes() {
fmt.Fprintf(os.Stdout, "Getting %s data from WP API...\n", t)
err := wpDataFromWpAPI(WPSiteURL, t, numberPerPage)
if err != nil {
return err
}
}
}
fmt.Println("Wordpress API data saved to disk...")
return nil
}
// wpDataFromWpAPI - access the data from the API for local store / processing
func wpDataFromWpAPI(URL string, contentType string, numberPerPage int) error {
_, err := url.ParseRequestURI(URL)
if err != nil {
//fmt.Println(err)
fmt.Println("Invalid URL. Must be in the format - http://...")
return err
}
i := 1
for {
// the url to the API
wpURL := fmt.Sprintf("%s/wp-json/wp/v2/%s?page=%d&per_page=%d", URL, contentType, i, numberPerPage)
fmt.Println(wpURL)
// Get the data
resp, err := http.Get(wpURL)
if err != nil {
return err
}
defer resp.Body.Close()
// send the filepath
apiOutputPath := fmt.Sprintf("data/api/%s", contentType)
outputFileName := fmt.Sprintf("%s-%d.json", contentType, i)
// if the response is ok, write a file
if resp.StatusCode == 200 {
// check the body length
body, _ := ioutil.ReadAll(resp.Body)
if len(body) < 10 {
break
}
// write the response body to a file
_, err := writeResponseToFile(apiOutputPath, outputFileName, body)
if err != nil {
return err
}
}
// break the loop if the link doesn't work
if resp.StatusCode != 200 {
break
}
i++
}
return nil
}
func writeResponseToFile(path string, filename string, content []byte) (int64, error) {
// check dir exists
if _, err := os.Stat(path); os.IsNotExist(err) {
os.MkdirAll(path, os.ModePerm)
}
// create a file path
file, fileErr := os.Create(filepath.Join(path, filename))
if fileErr != nil {
return 0, fileErr
}
defer file.Close()
// write to the file
numBytes, writeErr := io.Copy(file, bytes.NewReader(content))
//fmt.Println(numBytes)
return numBytes, writeErr
}