/
main.go
253 lines (218 loc) · 8.74 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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package main
import (
"context"
"database/sql"
"expvar"
"flag"
"fmt"
"os"
"runtime"
"strings"
"sync"
"time"
"github.com/cedrickchee/skel/internal/data"
"github.com/cedrickchee/skel/internal/jsonlog"
"github.com/cedrickchee/skel/internal/mailer"
// Import the pq driver so that it can register itself with the database/sql
// package. Note that we alias this import to the blank identifier, to stop
// the Go compiler complaining that the package isn't being used.
_ "github.com/lib/pq"
)
var (
// version contains the application version number. We'll generate this
// automatically at build time.
version string
// buildTime is a variable to hold the executable binary build time. Note
// that this must be a string type, as the -X linker flag will only work
// with string variables.
buildTime string
)
// Define a config struct to hold all the configuration settings for our
// application. For now, the only configuration settings will be the network
// port that we want the server to listen on, and the name of the current
// operating environment for the application (development, staging, production,
// etc.). We will read in these
// configuration settings from command-line flags when the application starts.
type config struct {
port int
env string
// Hold the configuration settings for the database connection pool, which
// we will read in from a command-line flag.
db struct {
dsn string
maxOpenConns int
maxIdleConns int
maxIdleTime string
}
// Struct contains fields for the requests-per-second and burst values, and
// a boolean field which we can use to enable/disable rate limiting
// altogether.
limiter struct {
rps float64
burst int
enabled bool
}
// Hold the SMTP server settings.
smtp struct {
host string
port int
username string
password string
sender string
}
// Hold the Cross-Origin Resource Sharing (CORS) policies.
cors struct {
trustedOrigins []string
}
}
// Define an application struct to hold the dependencies for our HTTP handlers,
// helpers, and middleware. At the moment this only contains a copy of the
// config struct and a logger, but it will grow to include a lot more as our
// build progresses.
type application struct {
config config
logger *jsonlog.Logger
models data.Models
mailer mailer.Mailer
wg sync.WaitGroup
}
func main() {
// Declare an instance of the config struct.
var cfg config
// Read the value of the port and env command-line flags into the config
// struct. We default to using the port number 4000 and the environment
// 'development' if no corresponding flags are provided.
flag.IntVar(&cfg.port, "port", 4000, "API server port")
flag.StringVar(&cfg.env, "env", "development", "Environment (development|staging|production)")
// Read the DSN value from the db-dsn command-line flag into the config
// struct. Use the empty string "" as the default value for the db-dsn
// command-line flag, rather than os.Getenv("SKEL_DB_DSN") like we were
// previously.
flag.StringVar(&cfg.db.dsn, "db-dsn", "", "PostgreSQL DSN")
// Read the connection pool settings from command-line flags into the config
// struct. Notice the default values that we're using?
flag.IntVar(&cfg.db.maxOpenConns, "db-max-open-conns", 25, "PostgreSQL max open connections")
flag.IntVar(&cfg.db.maxIdleConns, "db-max-idle-conns", 25, "PostgreSQL max idle connections")
flag.StringVar(&cfg.db.maxIdleTime, "db-max-idle-time", "15m", "PostgreSQL max idle time")
// Command line flags to read the rate limiter setting values into the
// config struct. Notice that we use true as the default for the "enabled"
// setting.
flag.Float64Var(&cfg.limiter.rps, "limiter-rps", 2, "Rate limiter maximum requests per second")
flag.IntVar(&cfg.limiter.burst, "limiter-burst", 4, "Rate limiter maximum burst")
flag.BoolVar(&cfg.limiter.enabled, "limiter-enabled", true, "Enable rate limiter")
// Read the SMTP server configuration settings into the config struct, using
// the Mailtrap settings as the default values.
flag.StringVar(&cfg.smtp.host, "smtp-host", "smtp.mailtrap.io", "SMTP host")
flag.IntVar(&cfg.smtp.port, "smtp-port", 2525, "SMTP port")
flag.StringVar(&cfg.smtp.username, "smtp-username", "b3754c2b680c33", "SMTP username")
flag.StringVar(&cfg.smtp.password, "smtp-password", "bd6fa5aaa2bd2f", "SMTP password")
flag.StringVar(&cfg.smtp.sender, "smtp-sender", "Skel <no-reply@example.com>", "SMTP sender")
// Use the flag.Func() function to process the -cors-trusted-origins command
// line flag. In this we use the strings.Fields() function to split the flag
// value into a slice based on whitespace characters and assign it to our
// config struct.
// Importantly, if the -cors-trusted-origins flag is not present, contains
// the empty string, or contains only whitespace, then strings.Fields() will
// return an empty []string slice.
flag.Func("cors-trusted-origins", "Trusted CORS origins (space separated)", func(val string) error {
cfg.cors.trustedOrigins = strings.Fields(val)
return nil
})
displayVersion := flag.Bool("version", false, "Display version and exit")
flag.Parse()
// If the version flag value is true, then print out the version number and
// immediately exit.
if *displayVersion {
fmt.Printf("Version:\t%s\n", version)
// Print out the contents of the buildTime variable.
fmt.Printf("Build time:\t%s\n", buildTime)
os.Exit(0)
}
// Initialize a new jsonlog.Logger which writes any messages *at or above*
// the INFO severity level to the standard out stream.
logger := jsonlog.New(os.Stdout, jsonlog.LevelInfo)
// Call the openDB() helper function (see below) to create the connection
// pool, passing in the config struct. If this returns an error, we log it
// and exit the application immediately.
db, err := openDB(cfg)
if err != nil {
// Use the PrintFatal() method to write a log entry containing the error
// at the FATAL level and exit. We have no additional properties to
// include in the log entry, so we pass nil as the second parameter.
logger.PrintFatal(err, nil)
}
// Defer a call to db.Close() so that the connection pool is closed before
// the main() function exits.
defer db.Close()
// Also log a message to say that the connection pool has been successfully
// established.
logger.PrintInfo("database connection pool established", nil)
// Publish a new 'version' variable in the expvar handler containing our
// application version number.
expvar.NewString("version").Set(version)
// Publish the number of active goroutines.
expvar.Publish("goroutines", expvar.Func(func() interface{} {
return runtime.NumGoroutine()
}))
// Publish the database connection pool statistics.
expvar.Publish("database", expvar.Func(func() interface{} {
return db.Stats()
}))
// Publish the current Unix timestamp.
expvar.Publish("timestamp", expvar.Func(func() interface{} {
return time.Now().Unix()
}))
// Declare an instance of the application struct, containing the config
// struct and the logger.
app := &application{
config: cfg,
logger: logger,
// Initialize a Models struct, passing in the connection pool as a
// parameter.
models: data.NewModels(db),
mailer: mailer.New(cfg.smtp.host, cfg.smtp.port, cfg.smtp.username,
cfg.smtp.password, cfg.smtp.sender),
}
// Start the HTTP server.
err = app.serve()
if err != nil {
logger.PrintFatal(err, nil)
}
}
// The openDB() function returns a sql.DB connection pool.
func openDB(cfg config) (*sql.DB, error) {
// Use sql.Open() to create an empty connection pool, using the DSN from the
// config struct.
db, err := sql.Open("postgres", cfg.db.dsn)
if err != nil {
return nil, err
}
// Set the maximum number of open (in-use + idle) connections in the pool.
// Note that passing a value less than or equal to 0 will mean there is no
// limit.
db.SetMaxOpenConns(cfg.db.maxOpenConns)
// Set the maximum number of idle connections in the pool. Again, passing a
// value less than or equal to 0 will mean there is no limit.
db.SetMaxIdleConns(cfg.db.maxIdleConns)
// Use the time.ParseDuration() function to convert the idle timeout
// duration string to a time.Duration type.
duration, err := time.ParseDuration(cfg.db.maxIdleTime)
if err != nil {
return nil, err
}
// Set the maximum idle timeout.
db.SetConnMaxIdleTime(duration)
// Create a context with a 5-second timeout deadline.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Use PingContext() to establish a new connection to the database, passing
// in the context we created above as a parameter. If the connection
// couldn't be established successfully within the 5 second deadline, then
// this will return an error.
err = db.PingContext(ctx)
if err != nil {
return nil, err
}
// Return the sql.DB connection pool.
return db, nil
}