This repository has been archived by the owner on Jul 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
list.go
108 lines (87 loc) · 2.51 KB
/
list.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
package google
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"github.com/spf13/viper"
"github.com/factly/x/errorx"
"github.com/factly/x/loggerx"
"github.com/factly/x/renderx"
)
// googleapis for factchecks
var GoogleURL = "https://factchecktools.googleapis.com/v1alpha1/claims:search"
// list response
type paging struct {
Total int `json:"total"`
Nodes []interface{} `json:"nodes"`
NextPage string `json:"nextPage"`
}
// list - Get all google fact checks
// @Summary Show all google fact checks
// @Description Get all google fact checks
// @Tags Claimant
// @ID get-all-google-fact-checks
// @Produce json
// @Param X-User header string true "User ID"
// @Param X-Space header string true "Space ID"
// @Param query query string false "Query"
// @Param pageToken query string false "Page Token"
// @Param language query string false "language code"
// @Param sort query string false "Sort"
// @Success 200 {object} paging
// @Router /fact-check/google [get]
func list(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("query")
language := r.URL.Query().Get("language")
pageToken := r.URL.Query().Get("pageToken")
if query == "" {
loggerx.Error(errors.New("query can't be empty"))
errorx.Render(w, errorx.Parser(errorx.Message{Message: "query can't be empty",
Code: http.StatusUnprocessableEntity}))
return
}
var factChecks map[string]interface{}
req, err := http.NewRequest("GET", GoogleURL, nil)
if err != nil {
loggerx.Error(err)
errorx.Render(w, errorx.Parser(errorx.InternalServerError()))
return
}
q := url.Values{}
q.Add("key", viper.GetString("google_key"))
q.Add("query", query)
if language != "" {
q.Add("languageCode", language)
}
if pageToken != "" {
q.Add("pageToken", pageToken)
}
req.URL.RawQuery = q.Encode()
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
loggerx.Error(err)
errorx.Render(w, errorx.Parser(errorx.NetworkError()))
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(body, &factChecks)
if err != nil {
loggerx.Error(err)
errorx.Render(w, errorx.Parser(errorx.DecodeError()))
return
}
result := paging{}
result.Nodes = make([]interface{}, 0)
if claims, found := factChecks["claims"]; found {
result.Nodes = (claims).([]interface{})
result.Total = len(result.Nodes)
}
if nextPageToken, found := factChecks["nextPageToken"]; found {
result.NextPage = nextPageToken.(string)
}
renderx.JSON(w, http.StatusOK, result)
}