-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
226 lines (189 loc) · 4.43 KB
/
main.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package main
import (
"database/sql"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
)
var db *sql.DB
var router *mux.Router
var addr = flag.String("addr", "localhost:3001", "http service address")
const (
dbhost = "localhost"
dbport = 5432
dbuser = "caninodev"
dbpass = "testing"
dbname = "lecheleccion"
)
type Article struct {
ID int
URL string
URLToImage string
Source string
PublicationDate time.Time
Title string
Body string
ExternalReferenceID int
CreatedAt time.Time
UpdatedAt time.Time
}
type BiasMeta struct {
ID int
Librt float32
Grn float32
Lbrl float32
Cnsvrt float32
biasableType string
biasableID int
createdAt time.Time
updatedAt time.Time
}
type ArticlesMessage struct {
Articles []Article
Librt float32
Grn float32
Lbrl float32
Cnsvrt float32
}
func main() {
initConnDB()
defer db.Close()
createRouter()
}
func createRouter() {
router = mux.NewRouter()
router.HandleFunc("/api/articles", GetArticles).Methods("GET")
router.HandleFunc("/api/{requestType}/{id}", HandleType).Methods("GET")
router.HandleFunc("/api/user/{id}", GetUser).Methods("GET")
log.Fatal(http.ListenAndServe(":3001", router))
}
func HandleType(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
var jsonData []byte
var err error
articleID := params["id"]
switch params["requestType"] {
case "article":
data, err := queryArticle(articleID)
if err == nil {
w.WriteHeader(http.StatusOK)
}
jsonData, err = json.Marshal(data)
case "bias":
data, err := queryBias(articleID)
if err == nil {
w.WriteHeader(http.StatusOK)
}
jsonData, err = json.Marshal(data)
default:
w.WriteHeader(http.StatusBadRequest)
err = json.NewEncoder(w).Encode([]byte("Malformed params. Please try again."))
}
_, err = w.Write(jsonData)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(err)
}
}
func (a *ArticlesMessage) queryAverages() {
sqlStatement := `SELECT AVG(t.Libertarian) AS "Libertarian", AVG(t.Green) AS "Green", AVG(t.Liberal) AS "Liberal", AVG(t.Conservative) AS "Conservative" FROM collections.biases t;`
row := db.QueryRow(sqlStatement)
err := row.Scan(
&a.Librt,
&a.Grn,
&a.Lbrl,
&a.Cnsvrt,
)
if err != nil {
log.Print(err)
}
}
func GetArticles(w http.ResponseWriter, r *http.Request) {
var msg ArticlesMessage
msg.Articles = queryArticles()
msg.queryAverages()
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(msg)
}
func GetUser(w http.ResponseWriter, r *http.Request) {
// ...
}
func queryArticles() []Article {
var articles []Article
sqlStatement := `SELECT t.* FROM collections.articles t LIMIT 50`
rows, err := db.Query(sqlStatement)
if err != nil {
log.Print("Error: ", err)
}
defer rows.Close()
for rows.Next() {
article := Article{}
err = rows.Scan(
&article.ID,
&article.URL,
&article.URLToImage,
&article.Source,
&article.PublicationDate,
&article.Title,
&article.Body,
&article.ExternalReferenceID,
&article.CreatedAt,
&article.UpdatedAt)
articles = append(articles, article)
}
return articles
}
func queryArticle(articleID string) (Article, error) {
article := Article{}
log.Print(articleID)
sqlStatement := `SELECT t.* FROM collections.articles t WHERE id = $1`
row := db.QueryRow(sqlStatement, articleID)
err := row.Scan(
&article.ID,
&article.URL,
&article.URLToImage,
&article.Source,
&article.PublicationDate,
&article.Title,
&article.Body,
&article.ExternalReferenceID,
&article.CreatedAt,
&article.UpdatedAt)
return article, err
}
func queryBias(articleID string) (BiasMeta, error) {
var bias BiasMeta
sqlStatement := `SELECT t.* FROM collections.biases t WHERE biasable_id = $1`
row := db.QueryRow(sqlStatement, articleID)
err := row.Scan(
&bias.ID,
&bias.Librt,
&bias.Grn,
&bias.Lbrl,
&bias.Cnsvrt,
&bias.biasableType,
&bias.biasableID,
&bias.createdAt,
&bias.updatedAt)
return bias, err
}
func initConnDB() {
var err error
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
dbhost, dbport,
dbuser, dbpass, dbname)
db, err = sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Println("Successfully connected!")
}