How to Build a REST API with Chi in Go

Web
Build a REST API in Go using the Chi router by importing the package, defining handlers, and mounting routes to the router instance.

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)
}
  1. Install the Chi router package using go get github.com/go-chi/chi/v5.
  2. Create a new router instance with r := chi.NewRouter().
  3. Define a handler function that accepts http.ResponseWriter and *http.Request.
  4. Mount the handler to a route using r.Get("/path", handler).
  5. Start the server with http.ListenAndServe(":3000", r).