go
36 lines · 7 steps
Handling a POST request in Gin
A Gin handler binds JSON, validates it, persists the article, and returns a 201 with a Location header.
Explained by
highlit
1func (h *ArticleHandler) Create(c *gin.Context) {
2 var req struct {
3 Title string `json:"title" binding:"required"`
4 Body string `json:"body" binding:"required"`
5 Tags []string `json:"tags"`
6 }
7
8 if err := c.ShouldBindJSON(&req); err != nil {
9 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
10 return
11 }
12
13 authorID := c.GetInt64("user_id")
14
15 article, err := h.articles.Create(c.Request.Context(), store.NewArticle{
16 Title: req.Title,
17 Body: req.Body,
18 Tags: req.Tags,
19 AuthorID: authorID,
20 })
21 if err != nil {
22 c.JSON(http.StatusInternalServerError, gin.H{"error": "could not create article"})
23 return
24 }
25
26 location := fmt.Sprintf("/api/v1/articles/%d", article.ID)
27 c.Header("Location", location)
28 c.JSON(http.StatusCreated, gin.H{
29 "id": article.ID,
30 "title": article.Title,
31 "body": article.Body,
32 "tags": article.Tags,
33 "author_id": article.AuthorID,
34 "created_at": article.CreatedAt,
35 })
36}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Binding tags let Gin parse and validate the request body in a single call, so invalid input never reaches your business logic.
- 2Handlers should distinguish client errors (400) from server errors (500) to give callers accurate feedback.
- 3Returning 201 with a Location header follows REST conventions for signalling where the newly created resource lives.
Related explainers
typescript
import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
go
package handlers import ( "net/http"
Serving embedded static meta files in Gin
embedding
static assets
http caching
Intermediate
6 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
go
package scheduler import ( "container/heap"
A priority job queue with Go's container/heap
priority-queue
heap
interfaces
Intermediate
9 steps
typescript
import { parsePhoneNumberFromString, CountryCode } from 'libphonenumber-js'; export interface NormalizedPhone { e164: string;
Normalizing phone numbers to E.164 in TypeScript
validation
normalization
error-handling
Intermediate
7 steps
php
<?php namespace App\Http\Controllers;
Broadcasting typing indicators in Laravel
websockets
authorization
presence-channels
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/handling-a-post-request-in-gin-explained-go-a0fe/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.