-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (65 loc) · 1.37 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
package main
import (
"encoding/json"
"fmt"
"github.com/joho/godotenv"
"io"
"io/ioutil"
"log"
"net/http"
"os"
)
type Article struct {
Title string
}
type Response struct {
Data []Article
}
func homePage(w http.ResponseWriter, r *http.Request) {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
req, _ := http.NewRequest("GET",
"https://newsapi.org/v2/top-headlines?country=us", nil)
req.Header.Add("X-Api-Key", os.Getenv("NEWS-APIKEY"))
res, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Printf(err.Error())
panic(err)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
panic(err)
}
}(res.Body)
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
response := string(body)
responseBytes := []byte(response)
var jsonRes map[string]interface{}
_ = json.Unmarshal(responseBytes, &jsonRes)
arr := jsonRes["articles"].([]interface{})
var articles []Article
for i := range arr {
cur := arr[i].(map[string]interface{})
a := Article{cur["title"].(string)}
articles = append(articles, a)
}
respArticles := Response{articles}
b, err := json.Marshal(respArticles)
_, err = fmt.Fprintf(w, string(b))
if err != nil {
return
}
}
func handleRequests() {
http.HandleFunc("/", homePage)
log.Fatal(http.ListenAndServe(":8081", nil))
}
func main() {
handleRequests()
}