debug.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package gin
  5. import (
  6. "bytes"
  7. "html/template"
  8. "log"
  9. )
  10. func init() {
  11. log.SetFlags(0)
  12. }
  13. // IsDebugging returns true if the framework is running in debug mode.
  14. // Use SetMode(gin.ReleaseMode) to disable debug mode.
  15. func IsDebugging() bool {
  16. return ginMode == debugCode
  17. }
  18. var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int)
  19. func debugPrintRoute(httpMethod, absolutePath string, handlers HandlersChain) {
  20. if IsDebugging() {
  21. nuHandlers := len(handlers)
  22. handlerName := nameOfFunction(handlers.Last())
  23. if DebugPrintRouteFunc == nil {
  24. debugPrint("%-6s %-25s --> %s (%d handlers)\n", httpMethod, absolutePath, handlerName, nuHandlers)
  25. } else {
  26. DebugPrintRouteFunc(httpMethod, absolutePath, handlerName, nuHandlers)
  27. }
  28. }
  29. }
  30. func debugPrintLoadTemplate(tmpl *template.Template) {
  31. if IsDebugging() {
  32. var buf bytes.Buffer
  33. for _, tmpl := range tmpl.Templates() {
  34. buf.WriteString("\t- ")
  35. buf.WriteString(tmpl.Name())
  36. buf.WriteString("\n")
  37. }
  38. debugPrint("Loaded HTML Templates (%d): \n%s\n", len(tmpl.Templates()), buf.String())
  39. }
  40. }
  41. func debugPrint(format string, values ...interface{}) {
  42. if IsDebugging() {
  43. log.Printf("[GIN-debug] "+format, values...)
  44. }
  45. }
  46. func debugPrintWARNINGDefault() {
  47. debugPrint(`[WARNING] Now Gin requires Go 1.6 or later and Go 1.7 will be required soon.
  48. `)
  49. debugPrint(`[WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
  50. `)
  51. }
  52. func debugPrintWARNINGNew() {
  53. debugPrint(`[WARNING] Running in "debug" mode. Switch to "release" mode in production.
  54. - using env: export GIN_MODE=release
  55. - using code: gin.SetMode(gin.ReleaseMode)
  56. `)
  57. }
  58. func debugPrintWARNINGSetHTMLTemplate() {
  59. debugPrint(`[WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called
  60. at initialization. ie. before any route is registered or the router is listening in a socket:
  61. router := gin.Default()
  62. router.SetHTMLTemplate(template) // << good place
  63. `)
  64. }
  65. func debugPrintError(err error) {
  66. if err != nil {
  67. debugPrint("[ERROR] %v\n", err)
  68. }
  69. }