Simple REST API for managing a library catalog while practicing Go back-end fundamentals: HTTP routing with net/http, request handlers, database connectivity, and CRUD workflows on top of MySQL.
- Wiring environment-driven MySQL connections (
DSNvia.env). - Designing a minimal data model (
models.Book). - Implementing repository helpers for CRUD with
database/sql. - Building HTTP handlers that decode/encode JSON payloads.
- Registering method-aware routes using Go 1.22+ patterns and
http.ServeMux.
cmd/api/main.go # bootstrapper: load env, run server
internal/router # http.ServeMux wiring
internal/handlers # book CRUD handlers
internal/db # DB connection + queries
internal/models # Book struct definition
- Go 1.22+
- MySQL 8.x (or compatible)
github.com/go-sql-driver/mysqlgithub.com/joho/godotenv
- Copy
.env.example(or create a new.env) and defineDSNin the Go MySQL driver format, e.g.:DSN="user:password@tcp(127.0.0.1:3306)/library?parseTime=true"
- Create the
bookstable:CREATE TABLE books ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, author VARCHAR(255) NOT NULL, genre VARCHAR(100) NOT NULL, published_year INT NOT NULL, available BOOLEAN DEFAULT TRUE, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP );
- Install dependencies:
go mod tidy
go run ./cmd/apiServer listens on :8080.
curl -X POST http://localhost:8080/books \
-H "Content-Type: application/json" \
-d '{
"title": "The Pragmatic Programmer",
"author": "Andrew Hunt",
"genre": "Tech",
"published_year": 1999,
"available": true
}'curl http://localhost:8080/bookscurl http://localhost:8080/books/1curl -X PUT http://localhost:8080/books/1 \
-H "Content-Type: application/json" \
-d '{
"title": "Pragmatic Programmer (20th)",
"author": "Andy Hunt",
"genre": "Tech",
"published_year": 2019,
"available": true
}'curl -X DELETE http://localhost:8080/books/1- Add validation for request payloads (title length, year bounds).
- Swap
database/sqlhelpers for a repository interface + tests. - Add pagination/filtering to
GET /books. - Dockerize the API and the MySQL instance for quicker setup.