{"slug": "handling-json-requests-in-go", "title": "Handling JSON Requests in Go", "summary": "This article explains how to handle incoming JSON data in a Go server by decoding request bodies into structs using the standard library's `encoding/json` package. It provides a step-by-step tutorial that includes setting up a Go project, defining a `User` struct with JSON tags, and implementing a handler that decodes a POST request's body into the struct using `json.NewDecoder(r.Body).Decode(&user)`. The tutorial also covers error handling for invalid JSON and demonstrates testing the server with a `curl` command.", "body_md": "Previously, we learned how to return JSON responses from a Go server.\n\nBut APIs do not only send data — they also receive it.\n\nFrontend applications, mobile apps, and clients commonly send JSON data to servers through HTTP requests.\n\nIn this tutorial, we will learn how to handle JSON requests in Go by decoding request bodies into structs using Go's standard library.\n\nBy the end, you will understand:\n\n- how JSON request bodies work\n- how to decode JSON in Go\n- how POST requests work\n- how to process incoming client data\n\n## Prerequisites\n\nTo follow along, you should have:\n\n- Go installed\n- basic familiarity with Go syntax\n- understanding of the\n`net/http`\n\npackage - basic understanding of JSON responses\n\nYou can confirm if Go is installed by running:\n\n```\ngo version\n```\n\n## Step 1 — Create the Project\n\nCreate a new folder for the project:\n\n```\nmkdir go-json-requests\ncd go-json-requests\n```\n\nNow initialize a Go module:\n\n```\ngo mod init go-json-requests\n```\n\nThis creates a `go.mod`\n\nfile for managing project dependencies.\n\n## Step 2 — Create the Server File\n\nCreate a file called `main.go`\n\n.\n\nYour project structure should now look like this:\n\n```\ngo-json-requests/\n├─ go.mod\n└─ main.go\n```\n\n## Step 3 — Write the Server\n\nOpen `main.go`\n\nand add the following code:\n\n```\npackage main\n\nimport (\n    \"encoding/json\"\n    \"fmt\"\n    \"net/http\"\n)\n\ntype User struct {\n    Name string `json:\"name\"`\n}\n\nfunc userHandler(w http.ResponseWriter, r *http.Request) {\n    var user User\n\n    err := json.NewDecoder(r.Body).Decode(&user)\n    if err != nil {\n        http.Error(w, \"Invalid JSON\", http.StatusBadRequest)\n        return\n    }\n\n    fmt.Fprintf(w, \"Hello, %s!\\n\", user.Name)\n}\n\nfunc main() {\n    http.HandleFunc(\"/user\", userHandler)\n\n    fmt.Println(\"Server running on :8080\")\n\n    http.ListenAndServe(\":8080\", nil)\n}\n```\n\nNow let's unpack what is happening.\n\n## Understanding POST Requests\n\nIn the previous examples, we mainly worked with routes that returned data.\n\nThis time, the client sends data to the server.\n\nThis commonly happens using a `POST`\n\nrequest.\n\nPOST requests are used when:\n\n- submitting forms\n- sending JSON data\n- creating resources\n- uploading information to a server\n\n## Understanding the Struct\n\nThis struct defines the shape of the JSON data we expect:\n\n```\ntype User struct {\n    Name string `json:\"name\"`\n}\n```\n\nIf the client sends:\n\n```\n{\n  \"name\": \"Steve\"\n}\n```\n\nGo can decode that JSON into the struct.\n\nThe `json:\"name\"`\n\ntag tells Go which JSON field maps to the struct field.\n\n## Understanding Request Bodies\n\nWhen a client sends data to a server, the data is stored inside the request body.\n\nIn Go, we access it using:\n\n```\nr.Body\n```\n\nThe `Body`\n\ncontains the incoming JSON data from the client.\n\n## Decoding JSON Requests\n\nThis line is the heart of the server:\n\n```\njson.NewDecoder(r.Body).Decode(&user)\n```\n\nHere's what happens:\n\n-\n`NewDecoder(r.Body)`\n\nreads the incoming request body -\n`Decode(&user)`\n\nconverts the JSON into the struct -\n`&user`\n\npasses a pointer so Go can modify the struct value\n\nAfter decoding, the `user`\n\nvariable contains the client data.\n\n## So Why Do We Use `&user`\n\n?\n\nYou may notice this part:\n\n```\n&user\n```\n\nThe `&`\n\nsymbol means:\n\n\"Use the memory address of this variable.\"\n\nThe decoder needs direct access to the struct so it can fill in the fields with incoming JSON data.\n\nWithout the pointer, decoding would not work correctly.\n\n## Understanding Error Handling\n\nThis section checks whether the JSON request is valid:\n\n```\nif err != nil {\n    http.Error(w, \"Invalid JSON\", http.StatusBadRequest)\n    return\n}\n```\n\nIf decoding fails:\n\n- the server sends an error response\n- the request stops processing\n\nThis helps prevent invalid client data from crashing the application.\n\n## Step 4 — Run the Server\n\nStart the application:\n\n```\ngo run main.go\n```\n\nYou should see:\n\n```\nServer running on :8080\n```\n\n## Step 5 — Test the API\n\nThis server expects a POST request containing JSON data.\n\nWe can test it using `curl`\n\n.\n\n```\ncurl -X POST http://localhost:8080/user \\\n-H \"Content-Type: application/json\" \\\n-d '{\"name\":\"Steve\"}'\n```\n\nYou should receive:\n\n```\nHello, Steve!\n```\n\n## What Happens When a Request Is Made?\n\nHere's the flow:\n\n- The client sends a POST request\n- JSON data is placed inside the request body\n- Go reads the request body\n- The JSON is decoded into a struct\n- The server processes the data\n- A response is sent back to the client\n\nThis is the foundation of many real-world APIs.\n\n## Where to Go Next\n\nNow that we can decode JSON requests, we could extend this server by adding:\n\n- multiple API endpoints\n- JSON responses\n- CRUD operations — again, because every backend journey eventually leads there\n- databases\n- request validation\n- authentication\n\nThis is where backend development starts becoming much more interactive and dynamic.\n\n## Final Thoughts\n\nWe started with a simple server that only returned data.\n\nNow our server can also receive and process JSON requests from clients.\n\nAlong the way, we learned about:\n\n- POST requests\n- request bodies\n- JSON decoding\n- structs\n- pointers\n- error handling\n\nThese concepts are essential when building APIs in Go.\n\nThanks for reading!\n\nHappy coding!", "url": "https://wpnews.pro/news/handling-json-requests-in-go", "canonical_source": "https://dev.to/steve_omollo/handling-json-requests-in-go-23mc", "published_at": "2026-05-23 11:59:27+00:00", "updated_at": "2026-05-23 12:32:31.665756+00:00", "lang": "en", "topics": ["developer-tools"], "entities": [], "alternates": {"html": "https://wpnews.pro/news/handling-json-requests-in-go", "markdown": "https://wpnews.pro/news/handling-json-requests-in-go.md", "text": "https://wpnews.pro/news/handling-json-requests-in-go.txt", "jsonld": "https://wpnews.pro/news/handling-json-requests-in-go.jsonld"}}