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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Binding tags let Gin parse and validate the request body in a single call, so invalid input never reaches your business logic.
  2. 2Handlers should distinguish client errors (400) from server errors (500) to give callers accurate feedback.
  3. 3Returning 201 with a Location header follows REST conventions for signalling where the newly created resource lives.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Handling a POST request in Gin — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code