Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 39 ยท Getting Started

Your First Gin App

Install Gin with go get, write a hello-world server, understand gin.Default versus gin.New, gin.H, the Context and r.Run, and see how the same flow works with a runnable stand-in.

In this lesson you will install Gin, write a small server, run it, and understand every line. You will also build a runnable stand-in of the engine so the pieces (gin.Default, r.GET, c.JSON, r.Run) stop feeling like magic. If you want the big picture first, read What Is Gin?.

Install Go and create a module

Gin is a normal Go module. You need a recent Go toolchain (check with go version; Gin supports the current and previous Go releases). Create a folder and initialize a module:

Terminal
mkdir hello-gin
cd hello-gin
go mod init example.com/hello-gin
go get github.com/gin-gonic/gin

go mod init creates go.mod, the file that lists your dependencies. go get downloads Gin and its own dependencies, records the version in go.mod and the checksums in go.sum. Commit both files to version control, so every machine builds with the same versions.

Hello, Gin

Create main.go:

Go
package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()

	r.GET("/ping", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "pong",
		})
	})

	r.Run() // listen and serve on 0.0.0.0:8080
}

Start it with go run . and open http://localhost:8080/ping. You will see {"message":"pong"}. The terminal prints a log line for the request, because gin.Default() attaches a logger.

Line by line:

  • gin.Default() creates an engine (*gin.Engine) with two middleware already attached: the Logger, which prints one line per request, and Recovery, which turns a panic in a handler into a 500 response instead of crashing the server.
  • r.GET("/ping", handler) registers a handler for the GET method and the path /ping. There are matching POST, PUT, PATCH, DELETE, OPTIONS and HEAD methods.
  • The handler is func(c *gin.Context). It has no return value: you write the response by calling a method on the context.
  • c.JSON(status, value) encodes the value as JSON, sets Content-Type: application/json, and writes the status.
  • gin.H is map[string]any, a quick way to build a JSON object.
  • r.Run() starts the HTTP server. With no argument it listens on :8080, or on the port in the PORT environment variable if that is set. r.Run(":9000") picks a port explicitly. Run blocks and returns an error only when the server stops.

Always use the constants from net/http, such as http.StatusOK and http.StatusNotFound, instead of bare numbers. They are self-documenting.

gin.Default versus gin.New

Go
r := gin.New()        // no middleware at all
r := gin.Default()    // gin.New() + Logger() + Recovery()

Use gin.Default() while learning and for most services. Choose gin.New() when you want full control, for example to attach a structured JSON logger of your own instead of the default text logger. Middleware and Logger and Recovery explain how.

A runnable stand-in for the engine

This program has the same shape as the Gin version: create an engine, register a route, hand it requests. It uses only the standard library, so you can run it here. It has a Default() that attaches a tiny logger, mirroring what gin.Default() does.

Go Stand-in: an engine with Default, GET and a logger

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first line, //go:debug httpmuxgo121=0, is a special comment that turns on the Go 1.22 router patterns (GET /path, ) on this site's runner, which compiles single files without a go.mod. In a real module with a recent go line you do not need it.

Notice ServeHTTP. It is the one method http.Handler requires, and it is why a Gin engine can be passed to http.ListenAndServe(":8080", r) or to your own http.Server. r.Run(addr) in Gin is literally a convenience wrapper around that call.

Running with your own http.Server

r.Run() is fine for development, but in production you usually want timeouts and graceful shutdown, which need an explicit http.Server:

Go
srv := &http.Server{
	Addr:              ":8080",
	Handler:           r, // the *gin.Engine
	ReadHeaderTimeout: 5 * time.Second,
	ReadTimeout:       10 * time.Second,
	WriteTimeout:      15 * time.Second,
	IdleTimeout:       60 * time.Second,
}
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
	log.Fatal(err)
}

You will use this in the deployment chapter later. For now remember the rule: the engine is the handler; the server is standard Go.

Testing a route without a server

Because the engine is an http.Handler, you can test it with httptest, exactly like the stand-in does. No port is opened and nothing needs to be running:

Go
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/ping", nil)
r.ServeHTTP(w, req)
// w.Code == 200, w.Body.String() == `{"message":"pong"}`

This is the foundation of testing Gin handlers.

Try more: handling two routes

Go Stand-in: two routes and a path parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In real Gin the parameter is written /users/:id and read with c.Param("id"). The stand-in uses the standard library pattern /users/{id} because that is what ServeMux understands. The next chapter covers Gin's syntax in detail.

Common mistakes

  • Forgetting go mod init. go get fails outside a module. Run go mod init first.
  • Importing the wrong path. The import is github.com/gin-gonic/gin, and the package name is gin.
  • Writing the response twice. After c.JSON(...) the response is committed. Calling c.JSON again appends garbage and Gin logs a warning. Use return after an early response.
  • Port already in use. Another process holds :8080. Pick another port with r.Run(":9000") or the PORT variable.
  • Running blocking code after r.Run(). Run does not return until the server stops, so anything after it does not execute while the server is up.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which command adds Gin to a Go module?

    go get downloads the module and records the version in go.mod and go.sum.
  2. 2. What does gin.Default() attach that gin.New() does not?

    gin.Default() is gin.New() plus the Logger and Recovery middleware.
  3. 3. What port does r.Run() with no arguments use if PORT is not set?

    With no argument Gin listens on :8080, or on the port in the PORT environment variable if it exists.
  4. 4. Why can you pass a Gin engine to http.ListenAndServe?

    The engine has a ServeHTTP method, which is all http.Handler requires.
  5. 5. A handler calls c.JSON(200, ...) and then c.JSON(500, ...). What happens?

    Headers are sent with the first write. A second write cannot change the status, so return after you respond.

Summary

  • go mod init then go get github.com/gin-gonic/gin sets up a project.
  • gin.Default() is an engine with Logger and Recovery; gin.New() is bare.
  • Register routes with r.GET, r.POST and friends; handlers take *gin.Context and respond through it.
  • c.JSON(status, gin.H{...}) is the quickest way to answer with JSON.
  • r.Run() serves on :8080 (or PORT); production code wraps the engine in its own http.Server.
  • The engine is an http.Handler, so it can be tested with httptest without opening a port.

Next: Modes, Configuration and Environment shows how to switch between debug and release behavior.