-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
89 lines (75 loc) · 1.99 KB
/
app.go
File metadata and controls
89 lines (75 loc) · 1.99 KB
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
package main
import (
"fmt"
"log"
"slidingo/internal/request"
"slidingo/internal/server"
"slidingo/internal/state"
"time"
)
type App struct {
persistor state.AutosavingPersistor
server *server.HTTPServer
counter request.Counter
}
func NewApp(filePath, addr string, maxConcurrentRequestCount int, timeout, autosaveDuration, counterWindow time.Duration) *App {
persistor := state.NewAutosavingPersistor(filePath, autosaveDuration)
state, err := persistor.Load()
var counter request.Counter
if err != nil {
log.Println("no previous state is found")
counter = request.NewCounter(counterWindow)
} else {
log.Println("loading from previous state")
counter, err = request.NewCounterFromSnapshot(state, counterWindow)
if err != nil {
panic(fmt.Errorf("unable to load from previous state: %w", err))
}
}
httpServer := server.New(addr, maxConcurrentRequestCount, timeout, counter)
return &App{
counter: counter,
persistor: persistor,
server: httpServer,
}
}
func NewAppWithZeroState(filePath, addr string, maxConcurrentRequestCount int, timeout, autosaveDuration, counterWindow time.Duration) *App {
persistor := state.NewAutosavingPersistor(filePath, autosaveDuration)
counter := request.NewCounter(counterWindow)
httpServer := server.New(addr, maxConcurrentRequestCount, timeout, counter)
return &App{
counter: counter,
persistor: persistor,
server: httpServer,
}
}
func (a *App) Start() error {
a.persistor.Start(a.counter)
errorChan := make(chan error)
go func() {
if err := a.server.Start(); err != nil {
log.Printf("application is shutting down: %v", err)
errorChan <- err
return
}
errorChan <- nil
}()
err := <-errorChan
close(errorChan)
return err
}
func (a *App) Stop() error {
if err := a.server.Close(); err != nil {
return err
}
if err := a.persistor.Stop(); err != nil {
return err
}
return nil
}
func (s *App) SetTimeout(timeout time.Duration) {
s.server.SetTimeout(timeout)
}
func (s *App) Clear() {
s.counter.Clear()
}