Chuyển đến nội dung

Bài 24 · Databases and GORM

CRUD with GORM and Gin

Build a complete REST CRUD API in Gin with GORM: create, list, get, update (PUT and PATCH) and delete, correct status codes, error mapping and a runnable stand-in.

CRUD stands for Create, Read, Update, Delete, the four things you do to almost every kind of data. A REST API exposes them as five routes per resource. In this lesson you build them with Gin and GORM, paying attention to the details that separate a toy from a service: correct status codes, 404 versus 500, partial updates and not trusting the client.

The GORM and Gin code is read-only, since neither runs in the in-page runner. To let you see the HTTP behaviour, the runnable examples implement the same five routes over an in-memory store with net/http. Only the storage lines differ; the status codes and JSON shapes are identical. You should have read GORM Setup and Models first.

The five routes

Method and path Action Success status
POST /products create 201 Created
GET /products list 200 OK
GET /products/:id read one 200 OK
PUT /products/:id or PATCH update 200 OK
DELETE /products/:id delete 204 No Content

Input types

Never bind JSON straight into the database model: a client could set ID, CreatedAt or an IsAdmin field. Use a dedicated input struct with only the fields a client may send (validation tags are covered in the Binding and Validation chapter):

Go
type ProductInput struct {
	Name       string `json:"name" binding:"required,max=120"`
	SKU        string `json:"sku" binding:"required,max=40"`
	PriceCents int    `json:"price_cents" binding:"gte=0"`
}

Create and list

Go
func (s *Server) create(c *gin.Context) {
	var in ProductInput
	if err := c.ShouldBindJSON(&in); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	p := Product{Name: in.Name, SKU: in.SKU, PriceCents: in.PriceCents}
	if err := s.db.Create(&p).Error; err != nil {
		if errors.Is(err, gorm.ErrDuplicatedKey) {
			c.JSON(http.StatusConflict, gin.H{"error": "sku already exists"})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": "database error"})
		return
	}
	c.Header("Location", fmt.Sprintf("/products/%d", p.ID))
	c.JSON(http.StatusCreated, p)
}

func (s *Server) list(c *gin.Context) {
	var products []Product
	if err := s.db.Order("id").Find(&products).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "database error"})
		return
	}
	c.JSON(http.StatusOK, products)
}

Create(&p) fills p.ID and the timestamps after inserting. Returning the created object plus a Location header lets clients avoid a second request. gorm.ErrDuplicatedKey only appears if you enable TranslateError: true in gorm.Config; otherwise inspect the driver error. The status for a unique-constraint clash is 409 Conflict, not 500.

Read one: 404 is not an error

Go
func (s *Server) get(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "id must be a number"})
		return
	}
	var p Product
	err = s.db.First(&p, id).Error
	switch {
	case errors.Is(err, gorm.ErrRecordNotFound):
		c.JSON(http.StatusNotFound, gin.H{"error": "product not found"})
	case err != nil:
		c.JSON(http.StatusInternalServerError, gin.H{"error": "database error"})
	default:
		c.JSON(http.StatusOK, p)
	}
}

First returns gorm.ErrRecordNotFound when nothing matches (Find into a slice does not, it just yields an empty slice). Map "not found" to 404 and everything unexpected to 500, and keep database error text out of the response.

Update: PUT versus PATCH

PUT replaces the whole resource: the client sends every field. PATCH changes only the fields it sends. With Go's zero values this has a trap: Updates(Product{PriceCents: 0}) ignores zero fields, so you cannot set a price to 0 or a bool to false.

Go
// PUT: replace all client-editable fields, zero values included
s.db.Model(&p).Select("Name", "SKU", "PriceCents").Updates(Product{
	Name: in.Name, SKU: in.SKU, PriceCents: in.PriceCents,
})

// PATCH: pointers tell "absent" from "zero"
type ProductPatch struct {
	Name       *string `json:"name"`
	PriceCents *int    `json:"price_cents"`
}
updates := map[string]any{}
if patch.Name != nil       { updates["name"] = *patch.Name }
if patch.PriceCents != nil { updates["price_cents"] = *patch.PriceCents }
s.db.Model(&p).Updates(updates) // a map updates zero values too

A nil pointer means "field not sent"; a pointer to 0 means "set it to zero". Using a map for the update is the clean way to apply only the present fields.

Delete

Go
func (s *Server) remove(c *gin.Context) {
	id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
	res := s.db.Delete(&Product{}, id)
	if res.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "database error"})
		return
	}
	if res.RowsAffected == 0 {
		c.JSON(http.StatusNotFound, gin.H{"error": "product not found"})
		return
	}
	c.Status(http.StatusNoContent)
}

RowsAffected tells you whether anything existed. With a DeletedAt field this is a soft delete; use Unscoped().Delete to remove the row for good.

Run the whole API (stand-in)

This program implements all five routes with the same status codes over a map. Run it, then read the output against the table above.

Go A five-route CRUD API with correct status codes

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Look at the PATCH line: the price became 0, which the pointer technique makes possible. Look at the two DELETE lines: 204 the first time, 404 the second.

Concurrency and race conditions

Two clients may update the same row at once. GORM offers optimistic locking by adding a Version int column and Where("version = ?", v) to updates, and pessimistic locking with clause.Locking{Strength: "UPDATE"} inside a transaction. For counters, let the database do the arithmetic: Update("stock", gorm.Expr("stock - ?", 1)) rather than read, subtract in Go and write back.

Common mistakes

  • Returning 200 with an error body; clients and monitoring rely on status codes.
  • Using Save for partial updates: Save writes every field, overwriting what you did not load.
  • Binding to the model and letting clients set ID or Role.
  • Confusing "no rows" (First gives an error, Find does not) and treating it as a 500.
  • Skipping the 400 for a non-numeric id, which turns user mistakes into server errors.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Which status code should a successful POST that creates a resource return?

    201 says a new resource exists. Add a Location header pointing to it.
  2. 2. Why does Updates(Product{PriceCents: 0}) not set the price to 0 in GORM?

    Struct updates ignore zero values. Use a map, Select, or pointer fields to write zeros.
  3. 3. What does First return when no row matches?

    First returns ErrRecordNotFound, which you map to HTTP 404.
  4. 4. A DELETE succeeded and there is nothing to return. Which status fits best?

    204 means success without a body.
  5. 5. Why use pointer fields in a PATCH input struct?

    A nil pointer means the client did not send the field; a pointer to 0 or false means set it to that value.

Summary

  • Five routes cover CRUD; choose 201, 200, 204, 400, 404, 409 deliberately.
  • Bind into input structs, not models, and never trust client-set IDs or roles.
  • First signals "not found" with ErrRecordNotFound; map it to 404 and other errors to 500.
  • PATCH needs pointers or maps to distinguish absent fields from zero values; Save overwrites everything.
  • Let the database do arithmetic and use locking for concurrent updates.

Next: Queries, Filtering and Pagination

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.