@@ -32,42 +32,43 @@ import (
32
32
)
33
33
34
34
type Server struct {
35
- // Listen port
36
- Port uint64
37
- // Data source name
38
- DSN string
39
35
// Server options
40
- Opts ServerOpts
36
+ opts ServerOpts
41
37
// PostgreSQL connection
42
38
db * pg.DB
43
- // Server secret key
44
- secret string
45
39
// Mux router
46
40
router * mux.Router
47
41
// Compiled templates
48
42
templates map [string ]* template.Template
49
43
}
50
44
51
45
type ServerOpts struct {
46
+ // Listen port
47
+ Port uint64
48
+ // Data source name
49
+ DSN string
50
+ // HTTPS only traffic allowed
52
51
HTTPSOnly bool
52
+ // Server Secret key
53
+ Secret string
53
54
}
54
55
55
56
// Constructor for new Server.
56
- func NewServer (port uint64 , dsn string , secret string , opts ServerOpts ) * Server {
57
- _ , err := pg .ParseURL (dsn )
57
+ func NewServer (opts ServerOpts ) * Server {
58
+ _ , err := pg .ParseURL (opts . DSN )
58
59
if err != nil {
59
60
panic (err )
60
61
}
61
- return & Server {Port : port , DSN : dsn , secret : secret , Opts : opts }
62
+ return & Server {opts : opts }
62
63
}
63
64
64
65
// Open and check database connection.
65
66
func (s * Server ) connectDB () error {
66
- opt , err := pg .ParseURL (s .DSN )
67
+ o , err := pg .ParseURL (s . opts .DSN )
67
68
if err != nil {
68
69
return err
69
70
}
70
- s .db = pg .Connect (opt )
71
+ s .db = pg .Connect (o )
71
72
72
73
// XXX: Ping postgres connection
73
74
//if err = s.db.Ping(); err != nil {
@@ -90,7 +91,7 @@ func (s *Server) createSchema() error {
90
91
// Generates a hash with a static length suitable for CSRF middleware.
91
92
func (s * Server ) genHashFromSecret () []byte {
92
93
h := sha256 .New ()
93
- h .Write ([]byte (s .secret ))
94
+ h .Write ([]byte (s .opts . Secret ))
94
95
return h .Sum (nil )
95
96
}
96
97
@@ -141,10 +142,10 @@ func (s *Server) Init() {
141
142
csrfMiddleware := csrf .Protect (
142
143
s .genHashFromSecret (),
143
144
csrf .FieldName ("csrf_token" ),
144
- csrf .Secure (s .Opts .HTTPSOnly ),
145
+ csrf .Secure (s .opts .HTTPSOnly ),
145
146
)
146
147
s .router .Use (csrfMiddleware )
147
- if s .Opts .HTTPSOnly {
148
+ if s .opts .HTTPSOnly {
148
149
s .router .Use (RedirectToHTTPSMiddleware )
149
150
}
150
151
@@ -175,10 +176,10 @@ func (s *Server) Listen() error {
175
176
}
176
177
177
178
// Start the server
178
- if s .Opts .HTTPSOnly {
179
+ if s .opts .HTTPSOnly {
179
180
log .Println ("HTTPS only traffic allowed" )
180
181
}
181
- log .Printf ("Starting server on :%d" , s .Port )
182
- log .Fatal (http .ListenAndServe (fmt .Sprintf (":%d" , s .Port ), s .router ))
182
+ log .Printf ("Starting server on :%d" , s .opts . Port )
183
+ log .Fatal (http .ListenAndServe (fmt .Sprintf (":%d" , s .opts . Port ), s .router ))
183
184
return nil
184
185
}
0 commit comments