Skip to content

Go HTTP JSON Response: Manual vs Encoding

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Go HTTP JSON Response: Manual vs Encoding. We cover key concepts, practical examples, and best practices.

JSON responses in Go -- Send proper JSON from HTTP handlers using encoding/json instead of string formatting to avoid malformed output.

The Problem

Building JSON responses with fmt.Fprintf or string concatenation produces invalid JSON when strings contain quotes, newlines, or special characters. Always use encoding/json's Encoder for safe JSON serialization.

Wrong

func userHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(`{"name":"John","age":30}`))
}

Output:

$ curl http://localhost:8080/user
{"name":"John","age":30}
// No Content-Type header set
func userHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(map[string]interface{}{
        "name": "John", "age": 30,
    })
}

Output:

$ curl http://localhost:8080/user
{"age":30,"name":"John"}
// Correct JSON, proper Content-Type

Prevention

  • Always set Content-Type: application/json before writing the body
  • Use json.NewEncoder(w).Encode() for streaming JSON output
  • Use json.Marshal for small payloads with error checking
  • Use struct tags (json:"field_name") for controlled field naming
  • Never use string concatenation for JSON -- it will break

Common Mistakes with http json response

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks

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

**Why does Go's json encoder lowercase field names?**

By default, json.Marshal uses the struct field name. Use json:"fieldName" tags to control naming.

How do I pretty-print JSON?

Use json.MarshalIndent or set Encoder.SetIndent("", " ") on the encoder.

How do I omit empty fields?

Use the omitempty tag option: json:"field,omitempty". Use json:"-" to skip a field entirely.


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