Go Academy · Lesson

Response Helpers and Status Codes

c.JSON, c.AbortWithError, and error responses

Lesson 3 of 413 steps

Response Helpers and Status Codes is a free Go Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.

c.JSON

c.JSON(statusCode, obj) serialises obj to JSON and sets Content-Type to application/json. It is the most common response method.

c.JSON(http.StatusOK, gin.H{
    "id":   user.ID,
    "name": user.Name,
})

gin.H

gin.H is a shorthand for map[string]any. Use it for ad-hoc JSON objects without defining a struct.

c.JSON(200, gin.H{"message": "created", "id": id})

HTTP status constants

Use http.Status* constants instead of raw numbers for clarity:

c.JSON(http.StatusCreated, gin.H{"id": id})
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid input"})
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})

c.String and c.Data

Send plain text with c.String or arbitrary bytes with c.Data:

c.String(200, "Hello, %s!", name)
c.Data(200, "application/octet-stream", fileBytes)

c.File and c.FileAttachment

Serve a file from disk — inline or as a download:

c.File("./public/report.pdf")           // inline
c.FileAttachment("./report.pdf", "report.pdf") // download

c.Redirect

Send an HTTP redirect (301 permanent, 302 temporary):

c.Redirect(http.StatusMovedPermanently, "/new-url")

c.AbortWithStatus

Stop processing the request chain and write an empty response with the given status code. Unlike c.JSON, it calls Abort to prevent subsequent handlers from running.

c.AbortWithStatus(http.StatusUnauthorized)

c.Error

Attach errors to the context without writing a response. A middleware can collect these and write a unified error response at the end.

c.Error(fmt.Errorf("database error: %w", err))

Response headers

Set custom response headers before calling c.JSON or c.Data:

c.Header("X-Request-ID", requestID)
c.Header("Cache-Control", "max-age=3600")

Rendering XML

Gin also supports XML and YAML responses:

c.XML(200, user) // requires xml struct tags
c.YAML(200, user)

Custom response struct

Define a standard API response wrapper for consistent shape across all endpoints:

type APIResponse struct {
    Success bool   `json:"success"`
    Data    any    `json:"data,omitempty"`
    Error   string `json:"error,omitempty"`
}

Quick Check

What does c.AbortWithStatus do differently from c.Status?

Recap: Response Helpers

Key points:

  • c.JSON(statusCode, obj) is the primary JSON response method
  • Use http.Status* constants for clarity
  • c.AbortWithStatus stops the handler chain
  • Define a consistent APIResponse wrapper for all endpoints
Free to start

Learn Go with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Response Helpers and Status Codes” lesson free?

Yes — any 3 lessons of the Go Academy learning path, including “Response Helpers and Status Codes”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.

What will I learn in “Response Helpers and Status Codes”?

c.JSON, c.AbortWithError, and error responses You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Response Helpers and Status Codes” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Gin Router and Route Groups
  2. Request Binding and Validation
  3. Response Helpers and Status Codes
  4. Gin Middleware: Auth and Logging
← Back to Go Academy