Browse Source

add a debug output mode

This can be enabled in the config, but needs to be added in other
places.
master
Gibheer 1 year ago
parent
commit
cb13ceab8f
  1. 3
      main.go
  2. 19
      server.go

3
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

19
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)

Loading…
Cancel
Save