Skip to content

Gin Engine: Default vs New Router

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Gin Engine: Default vs New Router. We cover key concepts, practical examples, and best practices.

Gin engine initialization -- Choose between gin.Default() and gin.New() based on whether you need built-in Logger and Recovery middleware.

The Problem

gin.Default() includes Logger and Recovery middleware automatically. gin.New() creates a blank engine. Using Default() in production can leak request logs to stdout. Using New() without Recovery leaves your app vulnerable to panics.

Wrong

r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
    c.String(200, "pong")
})
r.Run()

Output:

$ curl http://localhost:8080/ping
pong
// Logs every request to stdout
r := gin.New()
r.Use(gin.Recovery())
r.Use(gin.LoggerWithWriter(logFile))
r.GET("/ping", func(c *gin.Context) {
    c.String(200, "pong")
})
r.Run()

Output:

$ curl http://localhost:8080/ping
pong
// Logs to file only

Prevention

  • Use gin.Default() for rapid prototyping
  • Use gin.New() + gin.Recovery() for production
  • Use gin.LoggerWithWriter() for custom logging output
  • Always include gin.Recovery() to catch panics
  • gin.Default() = gin.New() + Logger + Recovery

Common Mistakes with gin engine

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**What middleware does gin.Default() include?**

Logger (request logging) and Recovery (panic recovery). Both write to os.Stdout.

Can I remove middleware from gin.Default()?

Not directly. Use gin.New() and add only what you need with r.Use().

How do I log to a file instead of stdout?

Use gin.LoggerWithWriter(file) or gin.LoggerWithConfig(gin.LoggerConfig{Output: file}).


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro