|
|
|
@ -21,6 +21,7 @@ type (
|
|
|
|
|
Server struct {
|
|
|
|
|
db *sql.DB
|
|
|
|
|
routes map[string]Handler
|
|
|
|
|
debug bool
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Handler is a function receiving a Context to process a request.
|
|
|
|
@ -31,9 +32,10 @@ type (
|
|
|
|
|
// It contains a prepared transaction for usage and important details like
|
|
|
|
|
// the user account.
|
|
|
|
|
Context struct {
|
|
|
|
|
id string
|
|
|
|
|
req *http.Request
|
|
|
|
|
w http.ResponseWriter
|
|
|
|
|
id string
|
|
|
|
|
req *http.Request
|
|
|
|
|
w http.ResponseWriter
|
|
|
|
|
debug bool // print debug output to the console
|
|
|
|
|
|
|
|
|
|
username string
|
|
|
|
|
tx *sql.Tx
|
|
|
|
@ -59,13 +61,14 @@ type (
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// NewServer creates a new server handler.
|
|
|
|
|
func NewServer(db *sql.DB) (*Server, error) {
|
|
|
|
|
func NewServer(db *sql.DB, debug bool) (*Server, error) {
|
|
|
|
|
if db == nil {
|
|
|
|
|
return nil, fmt.Errorf("database connection is not set")
|
|
|
|
|
}
|
|
|
|
|
return &Server{
|
|
|
|
|
db: db,
|
|
|
|
|
routes: map[string]Handler{},
|
|
|
|
|
debug: debug,
|
|
|
|
|
}, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -96,6 +99,7 @@ func (s *Server) Handle(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
id: id,
|
|
|
|
|
req: r,
|
|
|
|
|
w: w,
|
|
|
|
|
debug: s.debug,
|
|
|
|
|
username: "unknown",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -172,6 +176,13 @@ func (c *Context) Logf(level, msg string, args ...interface{}) {
|
|
|
|
|
log.Printf("%s - %s - %s", c.id, level, fmt.Sprintf(msg, args...))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Debugf logs output only when the server is set into debug mode.
|
|
|
|
|
func (c *Context) Debugf(level, msg string, args ...interface{}) {
|
|
|
|
|
if c.debug {
|
|
|
|
|
log.Printf("%s - %s - %s", c.id, level, fmt.Sprintf(msg, args...))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Generate a useable request ID, so that it can be found in the logs.
|
|
|
|
|
func newIdent() (string, error) {
|
|
|
|
|
b := make([]byte, 16)
|
|
|
|
|