-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb_server.go
87 lines (70 loc) · 1.64 KB
/
web_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
79
80
81
82
83
84
85
86
87
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/fatih/color"
"github.com/kataras/iris"
)
// Server handles HTTP traffic
// and state management of data
type Server struct {
Launches Launches `json:"launches"`
Ticker time.Ticker `json:"ticker"`
UpdatedAt time.Time `json:"updated_at"`
Update chan bool `json:"update"`
StopUpdate chan bool `json:"stop"`
Bot Bot `json:"bot"`
}
func (s *Server) init() {
color.Yellow("Init: data")
s.fetchLaunches()
s.Bot = newBot()
s.Update = make(chan bool)
s.StopUpdate = make(chan bool)
color.Green("Init complete")
go s.interval()
}
func (s *Server) fetchLaunches() {
resp, err := http.Get("https://launchlibrary.net/1.4/launch/next/10&mode=verbose")
if err != nil {
fmt.Println("Failed to get launch data")
}
// Close the body when finished
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// Read resp into array
err = json.Unmarshal(body, &s.Launches)
if err != nil {
fmt.Println(err)
}
}
func (s *Server) interval() {
ticker := time.NewTicker(6 * time.Hour)
for {
select {
case <-s.Update:
s.fetchLaunches()
s.UpdatedAt = time.Now()
case <-ticker.C:
s.fetchLaunches()
s.UpdatedAt = time.Now()
}
}
}
func (s *Server) home(ctx iris.Context) {
ctx.ViewLayout("layout.html")
ctx.ViewData("Launches", s.Launches.Data)
if err := ctx.View("index.html"); err != nil {
ctx.Application().Logger().Infof(err.Error())
}
}
func (s *Server) homeJSON(ctx iris.Context) {
ctx.JSON(s.Launches)
}
func (s *Server) update(ctx iris.Context) {
s.Update <- true
ctx.WriteString("Done")
}