Handling JSON Post Request in Go: 5 Fatal Mistakes and How to Avoid Them

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Handling JSON Post Request in Go: Why Even Experienced Developers Fall into Traps

\n\n

Have you ever written a Go server that should accept JSON via a POST request, and suddenly received an empty structure or a fatal error? If yes — you are not alone. The question "Handling JSON Post Request in Go" on Stack Overflow has gathered tens of thousands of views and hundreds of answers. This is a real "pain point" of the community.

\n\n

In this article, we will not just break down how to correctly handle JSON POST requests. We will go through the top pitfalls that beginners and even pros step on. You will learn how to avoid typical mistakes, write clean code, and not spend hours on debugging. Let's go!

\n\n

Why JSON and Go Are Love at First Byte?

\n\n

Go (or Golang) was created for modern web services. The built-in package encoding/json is a powerful tool. But, like any powerful tool, it requires proper handling. The most common problem is a mismatch between the JSON sent by the client and the structure expected by the server.

\n\n

Let's start with the basics — the correct handler structure.

\n\n

Mistake #1: Forgetting to Close the Request Body

\n\n

The first thing you should do in any POST handler is always close the request body. This is not just good manners, it is a guarantee that your server will not leak memory.

\n\n
package main\n\nimport (\n    "encoding/json"\n    "net/http"\n)\n\ntype User struct {\n    Name  string `json:"name"`\n    Email string `json:"email"`\n}\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n    // IMPORTANT: close Body\n    defer r.Body.Close()\n\n    // ... rest of the code\n}
\n\n

Many beginners skip this line, and the server starts "eating" memory. Always use defer r.Body.Close() immediately after receiving the request.

\n\n

Mistake #2: Ignoring Request Method Validation

\n\n

Your handler should explicitly check that the request is POST, not GET or PUT. Otherwise, you risk getting a panic or strange behavior.

\n\n
func handler(w http.ResponseWriter, r *http.Request) {\n    defer r.Body.Close()\n\n    if r.Method != http.MethodPost {\n        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)\n        return\n    }\n\n    // ... then work with JSON\n}
\n\n

This simple rule will save you from many headaches. Always check the method — it's basic code hygiene.

\n\n

Mistake #3: Using a Non-Strict JSON Decoder

\n\n

By default, json.Decoder in Go does not throw an error if the JSON has extra fields that are not described in your structure. This can lead to you "swallowing" invalid data.

\n\n

The rescue recipe is to use json.Decoder with the DisallowUnknownFields option:

\n\n
func handler(w http.ResponseWriter, r *http.Request) {\n    defer r.Body.Close()\n\n    var user User\n\n    decoder := json.NewDecoder(r.Body)\n    // Enable strict mode\n    decoder.DisallowUnknownFields()\n\n    err := decoder.Decode(&user)\n    if err != nil {\n        http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)\n        return\n    }\n\n    // If there were extra fields in the JSON — we get an error\n    // This is protection against accidental typos in the API\n\n    w.WriteHeader(http.StatusOK)\n    json.NewEncoder(w).Encode(user)\n}
\n\n

This approach is especially useful when you are developing a public API. Clients will be grateful for clear errors.

\n\n

Mistake #4: Not Checking That JSON Is Not Empty

\n\n

Imagine: the client sends an empty request body. Your code will happily decode an empty JSON {} and create a structure with zero values. This may not be what you expect.

\n\n

The best practice is to check that the body is not empty and that all required fields are filled:

\n\n
func hand                

Blogs

Book Recommendations