Getting Started #
In this tutorial you are going to learn how to use Chi router to create HTTP endpoints in Go. We will also take a look at using middleware in Chi and grouping routes.
Installing Chi #
Setup a new Go project using go mod init ...
and install Chi using the following command.
go get -u github.com/go-chi/chi/v5
Writing HTTP Endpoints #
A good thing about Chi is its ease of use and minimal API. Creating an endpoint is as simple as follows.
- We start by creating a new router using
chi.NewRouter()
router := chi.NewRouter()
- We register a new
GET
endpoint with the path/
.
router.Get("/", func(writer http.ResponseWriter, request *http.Request) {
_, err := writer.Write([]byte("Hello World"))
if err != nil {
log.Println(err)
}
})
Notice that chi takes the standard http.HandlerFunc
as the handler function for an endpoint. FYI, http.HandlerFunc
underlying type declaration is type HandlerFunc func(ResponseWriter, *Request)
.
- Chi router implements
http.Handler
interface so you can directly use it withhttp.ListenAndServe
.
err := http.ListenAndServe(":3000", router)
if err != nil {
log.Println(err)
}
Here is the full working example.
package main
import (
"github.com/go-chi/chi/v5"
"log"
"net/http"
)
func main() {
// 1. Create a new router
router := chi.NewRouter()
// 2. Register an endpoint
router.Get("/", func(writer http.ResponseWriter, request *http.Request) {
_, err := writer.Write([]byte("Hello World"))
if err != nil {
log.Println(err)
}
})
// 3. Use router to start the server
err := http.ListenAndServe(":3000", router)
if err != nil {
log.Println(err)
}
}
HTTP Methods #
Writing endpoints with other HTTP methods (POST
, PUT
, DELETE
etc) is exactly like writing the GET
request above, chi provides functions for all of them.
router.Put()
router.Post()
router.Delete()
router.Patch()
For endpoints that have a request body, you would parse the body just like you parse with regular Go http package.
Path Parameters #
chi provides a function (chi.URLParam
) to get path parameters that are defined using curly brackets { }
.
router.Get("/user/{username}", func(writer http.ResponseWriter, request *http.Request) {
username := chi.URLParam(request, "username") // š getting path param
_, err := writer.Write([]byte("Hello " + username))
if err != nil {
log.Println(err)
}
})
In this example we define a GET endpoint that has a path parameter username
, we call chi.URLParam(request, "username")
to get the value of the path parameter.
To get query params from a request you can use the inbuilt Go functionality request.URL.Query()
.