/
main.go
230 lines (196 loc) · 7.67 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
package main
import (
"context"
"database/sql"
"expvar"
"flag"
"fmt"
"os"
"runtime"
"strings"
"sync"
"time"
"github.com/sum28it/green-light/internal/data"
"github.com/sum28it/green-light/internal/jsonlog"
"github.com/sum28it/green-light/internal/mailer"
"github.com/sum28it/green-light/internal/vcs"
// 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"
)
// Set version of application corresponding to value of vcs.Version.
var (
version = vcs.Version()
)
// Define a config struct.
type config struct {
port int
env string
// db struct field holds the configuration settings for our database connection pool.
// For now this only holds the DSN, which we read in from a command-line flag.
db struct {
dsn string
maxOpenConns int
maxIdleConns int
maxIdleTime string
}
// Add a new limiter struct containing fields for the request-per-second and burst
// values, and a boolean field which we can use to enable/disable rate limiting.
limiter struct {
rps float64
burst int
enabled bool
}
smtp struct {
host string
port int
username string
password string
sender string
}
cors struct {
trustedOrigins []string
}
}
// Define an application struct to hold dependencies for our HTTP handlers, helpers, and
// middleware.
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.
// We default to using our development DSN if no flag is provided.
pw := os.Getenv("DB_PW")
flag.StringVar(&cfg.db.dsn, "db-dsn",
fmt.Sprintf("postgres://greenlight:%s@localhost/greenlight?sslmode=disable",
pw), "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 open idle connections")
flag.StringVar(&cfg.db.maxIdleTime, "db-max-idle-time", "15m",
"PostgreSQL max connection idle time")
// Read the limiter settings from the command-line flags into the config struct.
// We use true as the default for '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 teh default values.
mtUser := os.Getenv("MAILTRAP_USER")
mtPw := os.Getenv("MAILTRAP_PW")
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", mtUser, "SMTP username")
flag.StringVar(&cfg.smtp.password, "smtp-password", mtPw, "SMTP password")
flag.StringVar(&cfg.smtp.sender, "smtp-sender", "DoNotReply <3fc3f54366-09689f+1@inbox.mailtrap.io>", "SMTP sender")
// Use flag.Func function to process the -cors-trusted-origins command line flag. In this we
// use the strings.Field function to split the flag value into 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)
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.NewLogger(os.Stdout, jsonlog.LevelInfo)
// Call the openDB() helper function (see below) to create teh 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 {
logger.PrintFatal(err, nil)
}
// Defer a call to db.Close() so that the connection pool is closed before the main()
// function exits.
defer func() {
if err := db.Close(); err != nil {
logger.PrintFatal(err, nil)
}
}()
logger.PrintInfo("database connection pool established", nil)
// Publish a new "version" varaible in the expar var handler containing our application
// version number.
expvar.NewString("version").Set(version)
// Publish the number of activate 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 infoLog.
app := &application{
config: cfg,
logger: logger,
models: data.NewModels(db),
mailer: mailer.New(cfg.smtp.host, cfg.smtp.port, cfg.smtp.username, cfg.smtp.password, cfg.smtp.sender),
}
// Call app.server() to start the server.
if err := app.serve(); err != nil {
logger.PrintFatal(err, nil)
}
}
// openDB returns a sql.DB connection pool to postgres database
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 connection 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 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
}