-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.go
92 lines (76 loc) · 1.88 KB
/
route.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
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"math"
"net/http"
"net/url"
"strconv"
)
func indexHandler(w http.ResponseWriter, r *http.Request) {
tpl.Execute(w, nil)
}
func searchHandler(w http.ResponseWriter, r *http.Request) {
u, err := url.Parse(r.URL.String())
if err != nil {
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
params := u.Query()
searchKey := params.Get("q")
page := params.Get("page")
if page == "" {
page = "1"
}
s := &searchNews{}
s.SearchKey = searchKey
next, err := strconv.Atoi(page)
if err != nil {
http.Error(w, "unexpected server error", http.StatusInternalServerError)
return
}
s.NextPage = next
const (
URL = "https://newsapi.org/v2/everything?q=%s&pageSize=%d&page=%d&apiKey=%s&sortBy=publishedAt&language=en"
pageSize = 20
)
endpoint := fmt.Sprintf(URL, url.QueryEscape(s.SearchKey), pageSize, s.NextPage, *apiKey)
if err := fetch(endpoint, &s.Results); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
s.TotalPages = totalPages(s.Results.TotalResults, pageSize)
if ok := !s.IsLastPage(); ok {
s.NextPage++
}
if err := tpl.Execute(w, s); err != nil {
log.Fatal(err)
}
}
func fetch(endpoint string, v interface{}) error {
resp, err := http.Get(endpoint)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return errors.New("could not fetch data")
}
dec := json.NewDecoder(resp.Body)
if resp.StatusCode != http.StatusOK {
var newsErr newsAPIError
if err := dec.Decode(&newsErr); err != nil {
log.Println(err.Error())
return errors.New("json decoding error")
}
return errors.New(newsErr.Message)
}
if err := dec.Decode(v); err != nil {
log.Println(err.Error())
return errors.New("json decoding error")
}
return nil
}
func totalPages(total, pageSize int) int {
return int(math.Ceil(float64(total / pageSize)))
}