Core Concepts of Go for API Development
· One min read
If code doesn’t need HTTP, it doesn’t belong in an API handler...
Rule 1: Packages define ownership (and thus responsibility) for code. If code doesn’t need HTTP, it doesn’t belong in an API handler.
In otherwords, Handlers should not decide where data comes from. The application bootstrap (main.go) decides. Practical example:
- internal/store owns product logic
- internal/api/store owns HTTP concerns
- main / router only wires things together
Rule 2: Models can have behaviors (methods)
- Methods let data complete itself
- Major Benefit: This keeps handlers thin and readable (yah!)
Rule 3: If a method mutates state, use a pointer receiver.
func (p *Product) WithImage() { ... }
Product → copy
*Product → original object
