惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

大猫的无限游戏
大猫的无限游戏
阮一峰的网络日志
阮一峰的网络日志
T
Tailwind CSS Blog
WordPress大学
WordPress大学
小众软件
小众软件
Engineering at Meta
Engineering at Meta
有赞技术团队
有赞技术团队
博客园 - 聂微东
GbyAI
GbyAI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Stack Overflow Blog
Stack Overflow Blog
罗磊的独立博客
腾讯CDC
The Cloudflare Blog
博客园 - Franky
MongoDB | Blog
MongoDB | Blog
Martin Fowler
Martin Fowler
G
Google Developers Blog
博客园 - 三生石上(FineUI控件)
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

DEV Community

I tested 4 AI agent-governance tools against an open spec - here's the matrix zkML Inference Proof: What the Receipt Proves, and What the Model Still Does Not I Scored 1000/1000 on AWS Certified AI Practitioner (AIF-C01) Here's Every Resource I Used Go - Struct and Interface Storing Kamal secrets in AWS Secrets Manager and deploying to a cheap Hetzner VPS How I Caught and Fixed an N+1 Query in My Django REST API I got tired of paying $10/month to remove image backgrounds – so I built it for free How to Start Coding as a Student: A Complete Beginner’s Guide 🚀 Storing Kamal secrets in AWS Secrets Manager and deploying to a cheap Hetzner VPS What Are Buffers? Build AI Agents with Hot Dev The Client Onboarding Checklist That Prevents 90% of Project Problems Scalable Treasure Hunts Are a Myth, But We Almost Made One Gemini 3.5 Flash Has a 1M Token Context Window. Here's What You Can Actually Build With It. I built a ultra-polished developer portfolio template using React & Tailwind v4 (with zero-JSX configuration) Gemini CLI Is Dead. Here's the Better Thing That Replaced It Post-quantum cryptography for embedded and IoT: secure boot, TLS and OTA Understanding Optimistic Preloading in Modern Applications Nobody Wants to Read Your Code (And You Don't Want to Read Theirs) A clothing pairing app E2B vs E4B vs 31B Dense: The Practical Guide to Choosing the Right Gemma 4 Model I built an AI app store screenshot generator because Figma made me cry — looking for brutal feedback Hello DEV Community — My Developer Journey Begins Adaptable apps on ChromeOS: a post-mortem The WordPress Paradox: Why It’s Here to Stay (and How to Stop Ruining It) I built a local voice AI that can change to 9 different personalities! UXRay: I Built an AI That Roasts Your UI Like a Senior Designer Would Wyrly DI: Type-safe Dependency Injection for Modern TypeScript The contract is the interface: agent-driven Steampipe Stave in one command Gemma 4's Hidden Superpower: Why Built-in Thinking Tokens Change Everything for Evaluation Tasks ⚡ WordPress Performance: The Real Truth They Don't Tell You A Mobile App Usually Needs an Admin System First Customer Portals Should Remove Repeated Admin Work Episode 4: The Time Loop (Layers & Caching) I Built ContextForge with Gemma 4: A Project Memory Generator for Developers and AI Coding Agents Why shadow DOM beat iframe for inline tooltips HOW TO CREATE USER AND ASSIGN ROLES IN AZURE WITH ENTRA ID When AI Blackmail Goes Viral Episode 3: The Secret Scroll (The Dockerfile) Monte Carlo Simulation for Engineers: Turning Uncertainty Into Numbers The tokens-per-byte trap: character-level 'compression' adds tokens Nobody Reads Your Code Anymore Why I built a collection of 5 free, zero-signup career finance tools for solo builders 🚀 New React Challenge: Instant UI with useOptimistic Resolvendo a Alucinação da IA na Arquitetura de Software com Code Property Graphs e .NET 9 S1 — Clean Backtrace Crashes: How to Diagnose and Fix Them Cómo solucionar el bucle infinito en useEffect con objetos y arrays The Brutal Reality of Running Gemma 4 Locally I made Claude Code refuse to write code unless the ticket scores 80/100 I Fed React's Entire Hooks Transition History to Gemma 4. Here's What It Found That We Missed. Building a Private RAG System: Lessons from a Local-First AI Journal CodePulse AI — Reviving an AI-Powered Repository Intelligence Platform How to Split Video into Segments with FFmpeg (CLI + API) I've audited dozens of estate agency websites. The same 5 problems show up every single time. Part 1: Taming Asynchronous JavaScript: How to Build a "Mailbox" Queue Building My AI-Powered VS Code Extension 🚀 Google Login in Express with PassportJS & JWT Great example of Gemma 4 moving beyond chatbots into real-world decision support. Using AI to guide everyday actions like recycling shows how impactful applied LLMs can be when designed for usability, not just capability. #Gemma4 #AI #Sustainability Building a Production AI Chatbot for an Educational Institute: Architecture, Lessons & Full Stack Deep-Dive Google Login in Express with PassportJS & JWT How I reclaimed 47GB on my MacBook by cleaning developer project junk Operators Are Not Oracles: How We Learned to Stop Worrying and Love the Configuration I Built 6 Free Developer Tools for AI APIs, Cron, Docker, and Self-Hosting How I Built a Real-Time Precious Metals Price Feed for 30,000 Concurrent Users in Laravel How to Use a SERP API to Validate Whether a Project Idea Is Worth Building Gemma 4 discussions often focus on capability, but real-world impact depends on deployment context. For offline education, especially in low-connectivity regions, latency, cost, and local inference matter as much as model strength. Local Mind Explores it Space Complexity + Ω and Θ Notations Google I/O 2026 Just Confirmed the Shift From AI Chatbots to AI Agents How to Add API Monitoring to an Express App in 5 Minutes (2026) Designing an In-Game Inflation Tracking Algorithm for Web Utility Apps Google AI Studio Just Changed the Shape of App Development If you struggle to learn then this is for you. Best AI Agent Security & Guardrails Tools in 2026: LLM Guard vs NeMo vs Guardrails AI Building Dynamic RBAC in React 19: From Permission Strings to Component-Level Access Control How to Build a Self-Hosted AI Code Review Tool in Python Why We Switched from React to HTMX in Production: A 200-Site Case Study Gemma-Loom: The Intent-Based Virtual Machine (IVM) for Edge Sovereignty Java实习海投攻略:3天300个沟通,我是怎么拿到面试的 I Deployed Netflix's Web Server in 30 Seconds (And So Can You) - Docker Project 1 Debugging Android 14 WebRTC Disconnects on a coturn Relay Path 1/30 Days System Design Question Testing FastAPI + SQLAlchemy with Real PostgreSQL Fixtures: No More Mocking Misery FAQ Schema Markup Generators: What They Actually Do (and What They Don't Tell You) How a pure-TypeScript flex layout engine closed the last WASM-Yoga gap Spot instances as GitHub Actions runners Agents Need Receipts, Not Just Better Prompts readmegen — Generate beautiful README.md in seconds (12 templates, open source) When AI Reads Blueprints: The Hidden Attack Surface of Multimodal Engineering Intelligence Simplicity scales — complexity kills side projects AI does exactly what you ask — that's the problem How a model upgrade silently broke our extraction prompt (and how we caught it) The Best Form Backend for Static Sites in 2026 # ⛽ I Built a Cross-Platform Fuel Finder with React & Supabase: The Indie Dev Journey The 11 Major Cloud Service Providers in 2025 Membangun Karya Visual: Mengintip Fasilitas Multimedia dan Studio Kreatif Amikom What Is IOPS? Visualizing Database Design: From Interactive Canvas to Drizzle, Prisma, and SQL in Real-time A tool to make your GitHub README impossible to ignore 🚀 Zero-Downtime Blue-Green and IP-Based Canary Deployments on ECS Fargate I reproduced a Claude Code RCE. The bug pattern is everywhere.
Handling JSON Requests in Go
Steve Omollo · 2026-05-23 · via DEV Community

Previously, we learned how to return JSON responses from a Go server.

But APIs do not only send data — they also receive it.

Frontend applications, mobile apps, and clients commonly send JSON data to servers through HTTP requests.

In this tutorial, we will learn how to handle JSON requests in Go by decoding request bodies into structs using Go's standard library.

By the end, you will understand:

  • how JSON request bodies work
  • how to decode JSON in Go
  • how POST requests work
  • how to process incoming client data

Prerequisites

To follow along, you should have:

  • Go installed
  • basic familiarity with Go syntax
  • understanding of the net/http package
  • basic understanding of JSON responses

You can confirm if Go is installed by running:

go version

Enter fullscreen mode Exit fullscreen mode

Step 1 — Create the Project

Create a new folder for the project:

mkdir go-json-requests
cd go-json-requests

Enter fullscreen mode Exit fullscreen mode

Now initialize a Go module:

go mod init go-json-requests

Enter fullscreen mode Exit fullscreen mode

This creates a go.mod file for managing project dependencies.

Step 2 — Create the Server File

Create a file called main.go.

Your project structure should now look like this:

go-json-requests/
├─ go.mod
└─ main.go

Enter fullscreen mode Exit fullscreen mode

Step 3 — Write the Server

Open main.go and add the following code:

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

type User struct {
    Name string `json:"name"`
}

func userHandler(w http.ResponseWriter, r *http.Request) {
    var user User

    err := json.NewDecoder(r.Body).Decode(&user)
    if err != nil {
        http.Error(w, "Invalid JSON", http.StatusBadRequest)
        return
    }

    fmt.Fprintf(w, "Hello, %s!\n", user.Name)
}

func main() {
    http.HandleFunc("/user", userHandler)

    fmt.Println("Server running on :8080")

    http.ListenAndServe(":8080", nil)
}

Enter fullscreen mode Exit fullscreen mode

Now let's unpack what is happening.

Understanding POST Requests

In the previous examples, we mainly worked with routes that returned data.

This time, the client sends data to the server.

This commonly happens using a POST request.

POST requests are used when:

  • submitting forms
  • sending JSON data
  • creating resources
  • uploading information to a server

Understanding the Struct

This struct defines the shape of the JSON data we expect:

type User struct {
    Name string `json:"name"`
}

Enter fullscreen mode Exit fullscreen mode

If the client sends:

{
  "name": "Steve"
}

Enter fullscreen mode Exit fullscreen mode

Go can decode that JSON into the struct.

The json:"name" tag tells Go which JSON field maps to the struct field.

Understanding Request Bodies

When a client sends data to a server, the data is stored inside the request body.

In Go, we access it using:

r.Body

Enter fullscreen mode Exit fullscreen mode

The Body contains the incoming JSON data from the client.

Decoding JSON Requests

This line is the heart of the server:

json.NewDecoder(r.Body).Decode(&user)

Enter fullscreen mode Exit fullscreen mode

Here's what happens:

  • NewDecoder(r.Body) reads the incoming request body
  • Decode(&user) converts the JSON into the struct
  • &user passes a pointer so Go can modify the struct value

After decoding, the user variable contains the client data.

So Why Do We Use &user?

You may notice this part:

&user

Enter fullscreen mode Exit fullscreen mode

The & symbol means:

"Use the memory address of this variable."

The decoder needs direct access to the struct so it can fill in the fields with incoming JSON data.

Without the pointer, decoding would not work correctly.

Understanding Error Handling

This section checks whether the JSON request is valid:

if err != nil {
    http.Error(w, "Invalid JSON", http.StatusBadRequest)
    return
}

Enter fullscreen mode Exit fullscreen mode

If decoding fails:

  • the server sends an error response
  • the request stops processing

This helps prevent invalid client data from crashing the application.

Step 4 — Run the Server

Start the application:

go run main.go

Enter fullscreen mode Exit fullscreen mode

You should see:

Server running on :8080

Enter fullscreen mode Exit fullscreen mode

Step 5 — Test the API

This server expects a POST request containing JSON data.

We can test it using curl.

curl -X POST http://localhost:8080/user \
-H "Content-Type: application/json" \
-d '{"name":"Steve"}'

Enter fullscreen mode Exit fullscreen mode

You should receive:

Hello, Steve!

Enter fullscreen mode Exit fullscreen mode

What Happens When a Request Is Made?

Here's the flow:

  1. The client sends a POST request
  2. JSON data is placed inside the request body
  3. Go reads the request body
  4. The JSON is decoded into a struct
  5. The server processes the data
  6. A response is sent back to the client

This is the foundation of many real-world APIs.

Where to Go Next

Now that we can decode JSON requests, we could extend this server by adding:

  • multiple API endpoints
  • JSON responses
  • CRUD operations — again, because every backend journey eventually leads there
  • databases
  • request validation
  • authentication

This is where backend development starts becoming much more interactive and dynamic.

Final Thoughts

We started with a simple server that only returned data.

Now our server can also receive and process JSON requests from clients.

Along the way, we learned about:

  • POST requests
  • request bodies
  • JSON decoding
  • structs
  • pointers
  • error handling

These concepts are essential when building APIs in Go.

Thanks for reading!

Happy coding!