-
Notifications
You must be signed in to change notification settings - Fork 1
/
container.go
266 lines (237 loc) · 6.65 KB
/
container.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
254
255
256
257
258
259
260
261
262
263
264
265
266
// @Copyright (c) 2016 mparaiso <mparaiso@online.fr> All rights reserved.
package gonews
import (
"bytes"
"database/sql"
"encoding/json"
"html/template"
"log"
"net/http"
"os"
"fmt"
"errors"
"github.com/gorilla/sessions"
)
// Any is any value
type Any interface{}
// ContainerOptions are options provided to the container
type ContainerOptions struct {
DataSource,
Driver,
Secret,
Title,
Slogan,
Description,
TemplateDirectory string
Debug bool
SessionStoreFactory func() (sessions.Store, error)
ConnectionFactory func() (*sql.DB, error)
LoggerFactory func() (LoggerInterface, error)
csrfProvider CSRFProvider
user *User
}
// Container contains all the application dependencies
type Container struct {
ContainerOptions
db *sql.DB
logger LoggerInterface
threadRepository *ThreadRepository
userRepository *UserRepository
template TemplateProvider
session SessionInterface
}
// HasAuthenticatedUser returns true if a user has been authenticated
func (c *Container) HasAuthenticatedUser() bool {
return c.user != nil
}
// SetCurrentUser sets the authenticated user
func (c *Container) SetCurrentUser(u *User) {
c.user = u
}
// CurrentUser returns an authenticated user
func (c *Container) CurrentUser() *User {
return c.user
}
// GetSecret returns the secret key
func (c *Container) GetSecret() string {
return c.ContainerOptions.Secret
}
// GetTemplate returns *template.Template
func (c *Container) GetTemplate() (TemplateProvider, error) {
if c.template == nil {
tpl, err := template.New("templates").Funcs(template.FuncMap{
"IsDebug": func() bool {
return c.Debug
},
"ToJson": func(object Any) (string, error) {
b, err := json.MarshalIndent(object, "", "\t")
if err != nil {
return "", err
}
return bytes.NewBuffer(b).String(), err
},
}).ParseGlob(c.ContainerOptions.TemplateDirectory + "/*.tpl.html")
if err != nil {
return nil, err
}
c.template = &Template{Template: tpl}
}
return c.template, nil
}
// MustGetTemplate panics on error
func (c *Container) MustGetTemplate() TemplateProvider {
tpl, err := c.GetTemplate()
if err != nil {
panic(err)
}
return tpl
}
// GetConnection returns *sql.DB
func (c *Container) GetConnection() (*sql.DB, error) {
if c.ContainerOptions.ConnectionFactory != nil {
db, err := c.ContainerOptions.ConnectionFactory()
if err != nil {
return nil, err
}
c.db = db
} else if c.db == nil {
db, err := sql.Open(c.ContainerOptions.Driver, c.ContainerOptions.DataSource)
if err != nil {
return nil, err
}
c.db = db
}
return c.db, nil
}
// GetThreadRepository returns a repository for Thread
func (c *Container) GetThreadRepository() (*ThreadRepository, error) {
if c.threadRepository == nil {
db, err := c.GetConnection()
if err != nil {
return nil, err
}
c.threadRepository = &ThreadRepository{DB: db, Logger: c.MustGetLogger()}
}
return c.threadRepository, nil
}
// MustGetThreadRepository panics on error
func (c *Container) MustGetThreadRepository() *ThreadRepository {
r, err := c.GetThreadRepository()
if err != nil {
panic(err)
}
return r
}
// GetUserRepository returns a repository for User
func (c *Container) GetUserRepository() (*UserRepository, error) {
if c.userRepository == nil {
db, err := c.GetConnection()
if err != nil {
return nil, err
}
logger, err := c.GetLogger()
if err != nil {
return nil, err
}
c.userRepository = &UserRepository{db, logger}
}
return c.userRepository, nil
}
// MustGetUserRepository panics on error or return a repository of User
func (c *Container) MustGetUserRepository() *UserRepository {
r, err := c.GetUserRepository()
if err != nil {
panic(err)
}
return r
}
func (c *Container) GetCSRFProvider(request *http.Request) CSRFProvider {
if c.csrfProvider == nil {
c.csrfProvider = &DefaultCSRFProvider{c.MustGetSession(request), c.GetSecret()}
}
return c.csrfProvider
}
// GetOptions returns the container's options
func (c *Container) GetOptions() ContainerOptions {
return c.ContainerOptions
}
// GetLogger gets a logger
func (c *Container) GetLogger() (LoggerInterface, error) {
if c.logger == nil {
if c.ContainerOptions.LoggerFactory != nil {
logger, err := c.ContainerOptions.LoggerFactory()
if err != nil {
return nil, err
}
c.logger = logger
} else {
logger := &log.Logger{}
logger.SetOutput(os.Stdout)
c.logger = &Logger{logger, c.Debug}
}
}
return c.logger, nil
}
// MustGetLogger panics on error or return a LoggerInterface
func (c *Container) MustGetLogger() LoggerInterface {
logger, err := c.GetLogger()
if err != nil {
panic(err)
}
return logger
}
// HTTPError writes an error to the response
func (c *Container) HTTPError(rw http.ResponseWriter, r *http.Request, status int, message Any) {
c.MustGetLogger().Error(fmt.Sprintf("%s %d %s", r.URL, status, message))
rw.WriteHeader(status)
// if debug show a detailed error message
if c.Debug == true {
// if response has been sent, just write to output for now
// TODO buffer response in order to handle the case where there is
// an error in the template which should lead to a status 500
if rw.(ResponseWriterExtraInterface).IsResponseWritten() {
http.Error(rw, fmt.Sprintf("%v", message), status)
return
}
// if not then execute the template with the Message
c.MustGetTemplate().ExecuteTemplate(rw, "error.tpl.html", map[string]interface{}{"Status": status, "Message": message})
return
}
// if not debug show a generic error message.
// don't show a detailed error message
if rw.(ResponseWriterExtraInterface).IsResponseWritten() {
http.Error(rw, http.StatusText(status), status)
return
}
c.MustGetTemplate().ExecuteTemplate(rw, "error.tpl.html", map[string]interface{}{"Status": status, "Message": http.StatusText(status)})
}
// GetSessionStore returns a session.Store
func (c *Container) GetSessionStore() (sessions.Store, error) {
if c.ContainerOptions.SessionStoreFactory == nil {
return nil, errors.New("SessionStoreFactory not defined in Container.Options")
}
return c.ContainerOptions.SessionStoreFactory()
}
// GetSession returns the session
func (c *Container) GetSession(request *http.Request) (SessionInterface, error) {
if c.session == nil {
sessionStore, err := c.GetSessionStore()
if err != nil {
return nil, err
}
session, err := NewSession(sessionStore, request, "gonews-session")
if err != nil {
return nil, err
}
c.session = session
}
return c.session, nil
}
// MustGetSession panics on error
func (c *Container) MustGetSession(request *http.Request) SessionInterface {
session, err := c.GetSession(request)
if err != nil {
panic(err)
}
return session
}