-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
161 lines (134 loc) · 3.3 KB
/
main.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package main
import (
"context"
"errors"
"flag"
"fmt"
"html/template"
"log"
"net"
"net/http"
"os"
"os/signal"
"path"
"sync"
"syscall"
"time"
env "github.com/caarlos0/env/v9"
"github.com/joho/godotenv"
)
type config struct {
envfile string
Host string `env:"KUBICO_HOST" envDefault:"0.0.0.0"`
Port string `env:"KUBICO_PORT" envDefault:"8080"`
Cacheheaders bool `env:"KUBICO_NO_CACHE"`
Timeout int64 `env:"KUBICO_TIMEOUT_SECONDS"`
MaxRequests int64 `env:"KUBICO_MAX_REQUESTS"`
}
type application struct {
config *config
errorLog *log.Logger
infoLog *log.Logger
server *http.Server
wg sync.WaitGroup
stoppingCh chan string
templateCache map[string]*template.Template
}
func main() {
app := &application{
config: &config{},
stoppingCh: make(chan string, 1),
errorLog: log.New(os.Stderr, "ERROR\t", log.LUTC|log.Ldate|log.Ltime|log.Lshortfile),
infoLog: log.New(os.Stdout, "INFO\t", log.LUTC|log.Ldate|log.Ltime),
}
err := app.fetchConfig()
if err != nil {
app.errorLog.Fatal(err)
}
stopCh := make(chan struct{})
go func() {
msg := <-app.stoppingCh
if msg != "" {
app.infoLog.Println(msg)
}
close(stopCh)
}()
app.SetAppTimeout()
go func() {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
<-sigCh
select {
case app.stoppingCh <- "Got a OS interrupt signal":
default:
}
}()
templateCache, err := newTemplateCache()
if err != nil {
app.errorLog.Fatal(err)
}
app.templateCache = templateCache
app.Start()
defer app.Stop()
<-stopCh
}
func (app *application) Start() {
app.server = &http.Server{
Addr: net.JoinHostPort(app.config.Host, app.config.Port),
ErrorLog: app.errorLog,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
MaxHeaderBytes: 1 << 20,
Handler: app.noCacheHandler(app.routes()),
}
app.wg.Add(1)
go func() {
app.infoLog.Printf("Starting server on: http://%s:%s\n", app.config.Host, app.config.Port)
app.server.ListenAndServe()
app.wg.Done()
}()
}
func (app *application) Stop() error {
var err error
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
app.infoLog.Println("Trying to stop server gracefully...")
if err = app.server.Shutdown(ctx); err != nil {
if err = app.server.Close(); err != nil {
app.errorLog.Printf("Stopping server with error: %v\n", err)
return err
}
}
app.wg.Wait()
app.infoLog.Println("Server stopped")
return nil
}
func (app *application) fetchConfig() error {
envfile := flag.String("env-file", ".env", "Read in a file of environment variables")
flag.Parse()
app.config.envfile = path.Clean(*envfile)
err := godotenv.Load(app.config.envfile)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
app.infoLog.Print("No .env found.")
} else {
return err
}
} else {
app.infoLog.Printf("Loaded env-file from: %s", app.config.envfile)
}
if err := env.Parse(app.config); err != nil {
return err
}
return nil
}
func (app *application) SetAppTimeout() {
if app.config.Timeout > 0 {
time.AfterFunc(time.Duration(app.config.Timeout)*time.Second, func() {
select {
case app.stoppingCh <- fmt.Sprintf("Kubico timeout after %d seconds.", app.config.Timeout):
default:
}
})
}
}