Tillitsdone
down Scroll to discover

Building CRUD Operations with Chi and Go

Learn how to implement efficient CRUD operations using Chi router and Go, covering database integration, error handling, and best practices for building scalable web applications.
thumbnail

Building Robust CRUD Operations with Chi and Go: A Practical Guide

A minimalist geometric representation of database architecture featuring interconnected hexagonal nodes in neon blue and metallic silver colors with flowing data streams between them viewed from a 45-degree elevated angle high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

In today’s fast-paced development world, building efficient and scalable web applications is crucial. Go (Golang) has emerged as a powerful language for backend development, and when paired with the lightweight Chi router, it creates a formidable combination for building robust APIs. Let’s dive into creating a complete CRUD (Create, Read, Update, Delete) application using Chi and a database connection.

Setting Up Our Project Foundation

First, let’s structure our project properly. We’ll create a simple REST API for managing a book inventory system. This practical example will demonstrate real-world usage patterns and best practices.

Abstract 3D visualization of stacked cubes representing data storage rendered in bright sun-washed brick and breezeway blue colors floating in space captured from a low angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

package main
import (
"database/sql"
"net/http"
"github.com/go-chi/chi/v5"
_ "github.com/lib/pq"
)
type Book struct {
ID int `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
Year int `json:"year"`
}

Implementing CRUD Operations

Let’s break down each operation and see how Chi’s routing capabilities make our code clean and maintainable. We’ll implement handlers for creating, reading, updating, and deleting books.

// Create a new book
func createBook(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var book Book
json.NewDecoder(r.Body).Decode(&book)
query := `INSERT INTO books (title, author, year) VALUES ($1, $2, $3) RETURNING id`
err := db.QueryRow(query, book.Title, book.Author, book.Year).Scan(&book.ID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(book)
}
}

A flowing river of binary data represented by organic shapes and patterns colored in ochre and etched glass tones captured from a bird's eye view high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

The power of Chi shines through its middleware system. We can easily add authentication, logging, and error handling across our routes. Here’s how we set up our router with some basic middleware:

func setupRouter(db *sql.DB) *chi.Mux {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Route("/api/books", func(r chi.Router) {
r.Post("/", createBook(db))
r.Get("/", getBooks(db))
r.Get("/{id}", getBook(db))
r.Put("/{id}", updateBook(db))
r.Delete("/{id}", deleteBook(db))
})
return r
}

Error Handling and Best Practices

When working with databases, proper error handling is crucial. Here’s how we can implement a robust error handling system:

func handleDatabaseError(err error, w http.ResponseWriter) {
switch {
case err == sql.ErrNoRows:
http.Error(w, "Resource not found", http.StatusNotFound)
case err != nil:
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}

Conclusion

Building CRUD operations with Chi and Go provides a clean, efficient, and maintainable solution for web applications. The combination of Go’s simplicity and Chi’s flexibility makes it an excellent choice for modern web development.

A dynamic composition of interconnected geometric shapes representing system architecture rendered in metallic gold and whisper white colors viewed from a dramatic upward angle high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/code-outline.svg Golang Blogs
Programming language known for its simplicity, concurrency model, and performance.
icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.