/
wikidata.go
34 lines (32 loc) · 1 KB
/
wikidata.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
package utility
import (
// standard library
"encoding/json"
"io/ioutil"
"log"
"net/http"
"strconv"
)
// TitleFromID() calls the Wikidata API to get the title to a given ID.
func TitleFromID(ID int) (title string, err error) {
response, err := http.Get("https://www.wikidata.org/w/api.php?action=wbgetentities&ids=Q" + strconv.Itoa(ID) + "&format=json&languages=en&props=labels")
if err != nil {
log.Printf("Error calling Wikidata API: %v", err)
return
} else {
defer response.Body.Close()
body, e := ioutil.ReadAll(response.Body)
if e != nil {
log.Printf("Error reading Wikidata response: %v", err)
return
}
responseMap := make(map[string]interface{})
e = json.Unmarshal(body, &responseMap)
if e != nil {
log.Printf("Error unmarshaling Wikidata title: %v", err)
return
}
title = (((responseMap["entities"]).(map[string]interface{})["Q"+strconv.Itoa(ID)]).(map[string]interface{})["labels"]).(map[string]interface{})["en"].(map[string]interface{})["value"].(string)
}
return
}