You build a REST API with Chi by importing the router, defining handler functions, and mounting routes to the router instance.
package main
import (
"net/http"
"github.com/go-chi/chi/v5"
)
func main() {
r := chi.NewRouter()
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World"))
})
http.ListenAndServe(":3000", r)
}
- Install the Chi router package using
go get github.com/go-chi/chi/v5. - Create a new router instance with
r := chi.NewRouter(). - Define a handler function that accepts
http.ResponseWriterand*http.Request. - Mount the handler to a route using
r.Get("/path", handler). - Start the server with
http.ListenAndServe(":3000", r).