add a debug output mode

This can be enabled in the config, but needs to be added in other
places.
This commit is contained in:
Gibheer 2021-05-21 20:55:48 +02:00
parent 1696b6e15e
commit cb13ceab8f
2 changed files with 17 additions and 5 deletions

View File

@ -23,6 +23,7 @@ type (
Type string `toml:"type"` Type string `toml:"type"`
Connection string `toml:"conn"` Connection string `toml:"conn"`
} `toml:"db"` } `toml:"db"`
Debug bool `toml:"debug_mode"`
} }
) )
@ -59,7 +60,7 @@ func main() {
return return
} }
s, err := NewServer(db) s, err := NewServer(db, cfg.Debug)
if err != nil { if err != nil {
log.Fatalf("could not create server instance: %s", err) log.Fatalf("could not create server instance: %s", err)
return return

View File

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