-
Notifications
You must be signed in to change notification settings - Fork 1
/
wikipedia.go
100 lines (79 loc) · 2.13 KB
/
wikipedia.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 serendip
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"strconv"
)
const ENDPOINT = "https://ja.wikipedia.org/w/api.php"
const PSLIMIT = "3"
// get a random page of Wikipedia
func GetRandomPage() (int, string, string, error) {
// create request parameters
params := createParamsTemplate()
params.Set("list", "random")
params.Set("rnnamespace", "0")
params.Set("rnlimit", "1")
resp, err := requestWikipediaAPI(params)
if err != nil {
return 0, "", "", err
}
defer resp.Body.Close()
var result WikipediaRandomResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return 0, "", "", err
}
if len(result.Query.Random) == 0 {
return 0, "", "", fmt.Errorf("no random pages found")
}
page := &result.Query.Random[0]
return page.Id, page.Title, "https://ja.wikipedia.org/wiki/" + url.PathEscape(page.Title), nil
}
func GetPageContent(pageId int) (PageResult, error) {
params := createParamsTemplate()
params.Set("prop", "extracts")
params.Set("explaintext", "")
params.Set("exintro", "")
params.Set("redirects", "1")
params.Set("pageids", strconv.Itoa(pageId))
var result PageResult
resp, err := requestWikipediaAPI(params)
if err != nil {
return result, err
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&result)
return result, err
}
func SearchArticle(query string) (SearchResponse, error) {
params := createParamsTemplate()
params.Set("list", "prefixsearch")
params.Set("pssearch", query)
params.Set("pslimit", PSLIMIT)
var result SearchResponse
resp, err := requestWikipediaAPI(params)
if err != nil {
return result, err
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&result)
return result, err
}
func createParamsTemplate() url.Values {
params := url.Values{}
params.Set("action", "query")
params.Set("format", "json")
params.Set("utf8", "")
return params
}
func requestWikipediaAPI(params url.Values) (*http.Response, error) {
url := ENDPOINT + "?" + params.Encode()
log.Println("requested url:", url)
resp, err := http.Get(ENDPOINT + "?" + params.Encode())
if err != nil {
return resp, err
}
return resp, err
}