-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.go
77 lines (67 loc) · 1.64 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/waltzofpearls/rollie.dev/libs"
)
type App struct {
config *libs.Config
router *mux.Router
template *libs.Template
http *http.Server
errChan chan error
quitChan chan os.Signal
}
func NewApp(config *libs.Config) *App {
router := mux.NewRouter()
readTimeout := 10 * time.Second
writeTimeout := 20 * time.Second
handler := handlers.LoggingHandler(os.Stdout, router)
return &App{
config: config,
router: router,
template: libs.NewTemplate(config.Template.Path),
http: &http.Server{
Addr: config.Listen.HTTP,
Handler: handler,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
},
errChan: make(chan error),
quitChan: make(chan os.Signal, 1),
}
}
func (a *App) Run() {
origins := handlers.AllowedOrigins([]string{"*"})
a.router.Use(handlers.CORS(origins))
go func() {
log.Println("listening and serving HTTP")
if err := a.http.ListenAndServe(); err != nil {
a.errChan <- err
}
}()
signal.Notify(a.quitChan, syscall.SIGINT, syscall.SIGTERM)
select {
case err := <-a.errChan:
log.Println("HTTP server error:", err)
return
case sig := <-a.quitChan:
log.Println(sig.String(), "caught, shutting down")
return
}
}
func (a *App) UseStaticRouter(path string) {
fs := http.FileServer(http.Dir(path))
a.router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
}
func (a *App) UseRouter(path string, sr libs.Subroutable) {
s := a.router.PathPrefix(path).Subrouter()
sr.InitRouter(s, a.config, a.template)
sr.AttachHandlers()
}