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
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 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.