Backend development often involves repetitive boilerplate code, especially when dealing with database queries and API server implementations. Writing and maintaining this code manually can be error-prone and time-consuming. Code generation (codegen) tools help automate these tasks by generating type-safe, efficient, and maintainable code from declarative specifications.
In this article, we'll explore how to simplify backend logic in Go by using two popular codegen tools:
sqlc is a tool that generates Go code from SQL queries. You write your SQL queries in .sql
files, and sqlc generates Go functions that execute those queries with type-safe parameters and results.
sqlc.yaml
to specify input/output.sqlc generate
to produce Go code.Suppose you have a simple users
table:
And a query to get a user by email:
Your sqlc.yaml
config:
Run:
This generates Go code with a method like:
You can use it in your backend:
This eliminates manual SQL string handling and scanning rows, making your code cleaner and safer.
oapi-codegen generates Go server (and client) code from an OpenAPI (Swagger) specification. It creates interfaces and request/response types, so you can focus on implementing business logic.
oapi-codegen
to generate Go server code.Consider a simple OpenAPI spec api.yaml
:
Generate server code:
This generates:
User
struct)ServerInterface
with method:Implement the interface:
Wire up the server:
Using sqlc and oapi-codegen together can greatly simplify backend development in Go by automating the generation of database access and API server code. This approach reduces boilerplate, improves safety, and accelerates development, allowing you to focus on what matters most: your application's core logic.
© Melvin Laplanche - All rights reserved.