/
count.go
45 lines (38 loc) · 987 Bytes
/
count.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
package main
import (
"encoding/json"
"fmt"
"net/http"
// "github.com/bcampbell/scrapeomat/store"
)
type ArticleCountResult struct {
ArticleCount int `json:"article_count"`
}
// implement api/count
func (srv *SlurpServer) countHandler(ctx *Context, w http.ResponseWriter, r *http.Request) {
filt, err := getFilter(r)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
totalArts, err := srv.db.FetchCount(filt)
if err != nil {
// TODO: should send error via json?
http.Error(w, fmt.Sprintf("DB error: %s", err), 500)
return
}
msg := ArticleCountResult{ArticleCount: totalArts}
outBuf, err := json.Marshal(msg)
if err != nil {
errMsg := fmt.Sprintf("json encoding error: %s\n", err)
srv.ErrLog.Printf(errMsg)
http.Error(w, errMsg, 500)
return
}
_, err = w.Write(outBuf)
if err != nil {
srv.ErrLog.Printf("write error: %s\n", err)
return
}
srv.InfoLog.Printf("%s /api/count OK %d arts %s\n", r.RemoteAddr, totalArts, filt.Describe())
}