-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
58 lines (50 loc) · 1.04 KB
/
app.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
package gorouter
import (
"context"
"fmt"
"net/http"
"time"
)
type App struct {
s *http.Server
*Controller
}
// NewApp inits new app
func NewApp(o ...Options) *App {
opt := OptionsStruct{
Addr: PORT_DEFAULT,
WriteT: WRITE_DEFAULT,
ReadT: READ_DEFAULT,
}
for _, options := range o {
options(&opt)
}
ctrl := NewController()
router := NewRouter(ctrl)
s := &http.Server{
Addr: opt.Addr,
WriteTimeout: opt.WriteT,
ReadTimeout: opt.ReadT,
Handler: router,
}
return &App{
s: s,
Controller: ctrl,
}
}
// Listen starts http server with provided options in app
func (a *App) Listen() error {
fmt.Printf("Server listen on port: %s\n", a.s.Addr)
if err := a.s.ListenAndServe(); err != nil {
return fmt.Errorf("failed to listen: %w", err)
}
return nil
}
// Shutdown make graceful shutdown
func (a *App) Shutdown() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
if err := a.s.Shutdown(ctx); err != nil {
panic("failed to shutdown app: " + err.Error())
}
}