𝗕𝘂𝗶𝗹𝗱𝗶𝗻𝗴 𝗠𝘆 𝗙𝗶𝗿𝘀𝘁 𝗥𝗲𝗮𝗹 𝗔𝗣𝗜 𝗶𝗻 𝗚𝗼 𝘄𝗶𝘁𝗵 𝗚𝗶𝗻
I am moving from theory to practice.
After studying structs, interfaces, goroutines, and error handling, I built a working Orders API using Go and the Gin framework.
The API performs three tasks:
- Create an order
- Fetch an order by ID
- List all orders
I chose Gin because it simplifies routing and middleware. It provides helper functions like c.JSON and c.AbortWithStatusJSON. These tools remove repetitive code.
Project Structure: I used a flat package layout to keep things clean:
- handler: Manages HTTP logic.
- model: Defines data shapes.
- store: Handles data storage.
- middleware: Manages logging and requests.
Key Technical Choices:
• Data Validation I used struct tags for JSON serialization. I also used Gin binding tags. This ensures that required fields exist and amounts are greater than zero.
• Persistence and Concurrency The current version uses an in-memory store. I used a sync.RWMutex to manage concurrent access. This allows multiple reads but keeps writes safe.
• Interfaces The handler depends on the OrderStore interface. It does not care if the data lives in memory or a database. This makes swapping the storage layer easy.
• Error Handling I used errors.Is to check for specific errors like ErrNotFound. This allows the API to return a proper 404 status code to the user.
• Middleware I built a custom logger. It tracks the method, path, status code, and request duration.
This setup brings together everything learned in previous parts. It is a functional, structured, and scalable foundation.
How do you structure your Go projects? Do you prefer flat packages or deep, domain-driven nesting?
Source: https://dev.to/mihirmohapatra/building-my-first-real-api-in-go-with-gin-3kio