How to Use Chi Router in Go: Simple Guide with Examples
To use
chi router in Go, first import the github.com/go-chi/chi/v5 package, create a new router with chi.NewRouter(), then define routes using methods like Get or Post. Finally, start the HTTP server with http.ListenAndServe passing the router as the handler.Syntax
The basic syntax to use chi router involves creating a router instance, defining routes, and starting the server.
- chi.NewRouter(): Creates a new router.
- router.Method(path, handler): Defines a route for HTTP methods like GET, POST.
- http.ListenAndServe(address, router): Starts the HTTP server using the router.
go
package main import ( "net/http" "github.com/go-chi/chi/v5" ) func main() { r := chi.NewRouter() // create router r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, Chi!")) }) http.ListenAndServe(":8080", r) // start server }
Example
This example shows a simple web server using chi that responds to GET requests on the root path and a dynamic user path.
go
package main import ( "net/http" "github.com/go-chi/chi/v5" "fmt" ) func main() { r := chi.NewRouter() r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Welcome to Chi Router!")) }) r.Get("/user/{userID}", func(w http.ResponseWriter, r *http.Request) { userID := chi.URLParam(r, "userID") fmt.Fprintf(w, "User ID: %s", userID) }) http.ListenAndServe(":8080", r) }
Output
When you visit http://localhost:8080/ you see:
Welcome to Chi Router!
When you visit http://localhost:8080/user/123 you see:
User ID: 123
Common Pitfalls
Common mistakes when using chi router include:
- Not importing the correct
chi/v5package version. - Forgetting to call
http.ListenAndServewith the router as the handler. - Using incorrect route patterns or forgetting to extract URL parameters with
chi.URLParam. - Not handling errors from
ListenAndServe.
go
/* Wrong: Not passing router to ListenAndServe */ http.ListenAndServe(":8080", nil) // This will not use chi router /* Right: Pass router */ http.ListenAndServe(":8080", r)
Quick Reference
| Function | Description |
|---|---|
| chi.NewRouter() | Creates a new router instance |
| router.Get(path, handler) | Handles GET requests for the given path |
| router.Post(path, handler) | Handles POST requests for the given path |
| chi.URLParam(r, "param") | Extracts URL parameter from request |
| http.ListenAndServe(addr, handler) | Starts HTTP server with handler |
Key Takeaways
Import and use chi/v5 package to create a router with chi.NewRouter().
Define routes using router methods like Get and Post with path and handler.
Use chi.URLParam to get dynamic URL parameters inside handlers.
Pass the router as the handler to http.ListenAndServe to start the server.
Always check for common mistakes like missing router in ListenAndServe or wrong imports.