From cb13ceab8f274f939d8bda2f8d1d294dbdfaaae0 Mon Sep 17 00:00:00 2001 From: Gibheer Date: Fri, 21 May 2021 20:55:48 +0200 Subject: [PATCH] add a debug output mode This can be enabled in the config, but needs to be added in other places. --- main.go | 3 ++- server.go | 19 +++++++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 46d2405..a4e9b9a 100644 --- a/main.go +++ b/main.go @@ -23,6 +23,7 @@ type ( Type string `toml:"type"` Connection string `toml:"conn"` } `toml:"db"` + Debug bool `toml:"debug_mode"` } ) @@ -59,7 +60,7 @@ func main() { return } - s, err := NewServer(db) + s, err := NewServer(db, cfg.Debug) if err != nil { log.Fatalf("could not create server instance: %s", err) return diff --git a/server.go b/server.go index 551fcdb..ab16179 100644 --- a/server.go +++ b/server.go @@ -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)