-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
78 lines (67 loc) · 1.65 KB
/
server.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
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"github.com/gin-gonic/gin"
)
type headlines struct {
Author string
Title string
Description string
Url string
UrlToImage string
PublishedAt string
Content string
}
type NewsResponse struct {
Status string
TotalResults int
Code string
Message string
URL string
Articles []headlines
}
func GetSourceHeadlines(source string, newsAPIKey string) NewsResponse {
var newsResponse NewsResponse
url := "https://newsapi.org/v2/top-headlines?sources=" + source + "&apiKey=" + newsAPIKey
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
bodyBytes, _ := ioutil.ReadAll(resp.Body)
err := json.Unmarshal(bodyBytes, &newsResponse)
if err == nil {
return newsResponse
}
panic(err)
} else {
bodyBytes, _ := ioutil.ReadAll(resp.Body)
_ = json.Unmarshal(bodyBytes, &newsResponse)
newsResponse.URL = url
return newsResponse
}
}
func main() {
if len(os.Args) != 2 {
print("Usage: ./server <news-api-key>\n")
os.Exit(99)
}
r := gin.Default()
r.GET("/headlines/ign", func(c *gin.Context) {
c.JSON(http.StatusOK, GetSourceHeadlines("ign", os.Args[1]))
})
r.GET("/headlines/polygon", func(c *gin.Context) {
c.JSON(http.StatusOK, GetSourceHeadlines("polygon", os.Args[1]))
})
r.GET("/headlines/techcrunch", func(c *gin.Context) {
c.JSON(http.StatusOK, GetSourceHeadlines("techcrunch", os.Args[1]))
})
r.GET("/headlines/hacker-news", func(c *gin.Context) {
c.JSON(http.StatusOK, GetSourceHeadlines("hacker-news", os.Args[1]))
})
r.Run(":80")
}