Create a net/http Server from the generated code by the awesome sqlc project. If you’re searching for a SQLC plugin, use sqlc-gen-go-server.
- Go 1.23 or superior
- sqlc
go install github.com/sqlc-dev/sqlc/cmd/sqlc@latestgo install github.com/walterwanderley/sqlc-http@latestIf you want to generate a complete application (including htmx frontend), check this example.
- Create a queries.sql file:
--queries.sql CREATE TABLE authors ( id BIGSERIAL PRIMARY KEY, name text NOT NULL, bio text, created_at TIMESTAMP ); -- name: GetAuthor :one -- http: GET /authors/{id} SELECT * FROM authors WHERE id = $1 LIMIT 1; -- name: ListAuthors :many -- http: GET /authors SELECT * FROM authors ORDER BY name; -- name: CreateAuthor :one -- http: POST /authors INSERT INTO authors ( name, bio, created_at ) VALUES ( $1, $2, $3 ) RETURNING *; -- name: DeleteAuthor :exec -- http: DELETE /authors/{id} DELETE FROM authors WHERE id = $1; -- name: UpdateAuthorBio :exec -- http: PATCH /authors/{id}/bio UPDATE authors SET bio = $1 WHERE id = $2;- Create a sqlc.yaml file
version: "2" sql: - schema: "./queries.sql" queries: "./queries.sql" engine: "postgresql" gen: go: out: "internal/author"- Execute sqlc
sqlc generate- Execute sqlc-http
sqlc-http -m "mymodule"If you want to generate the frontend (htmx):
sqlc-http -m "mymodule" -frontend- Run the generated server
go run . -db [Database Connection URL] -dev- Enjoy!
If you do not generate the frontend in step 4?
- Swagger UI: http://localhost:5000/swagger
If you generate the frontend in step 4:
- HTMX frontend: http://localhost:5000
- Swagger UI: http://localhost:5000/static/swagger
You can customize the HTTP endpoints by adding comments to the queries.
-- http: Method PathHere’s an example of a queries file that has a custom HTTP endpoint:
-- name: ListAuthors :many -- http: GET /authors SELECT * FROM authors ORDER BY name; -- name: UpdateAuthorBio :exec -- http: PATCH /authors/{id}/bio UPDATE authors SET bio = $1 WHERE id = $2;-
It's safe to edit any generated code that doesn't have the
DO NOT EDITindication at the very first line. -
After modify a SQL file, execute these commands below:
sqlc generate go generate