DEV Community

Sam Newby
Sam Newby

Posted on

Using Chi as a router for Go APIs

The Go net/http package is great, it provides Go developers with a fantastic build block for building super fast APIs with Go.

However, it doesn't have a built in router that most developers would be used to. Luckily, a lot of community members have built really simple routers that can be used with the standard net/http package. There is a lot of options out there, but my personal favourite is Chi

Disclaimer: I'm not going to go into a lot of detail why I personally prefer Chi as I believe that those who are new to Go should be allowed to freely make there own choice on their favourite router without influence from others.

Right, let's take a look at how we can build a small API using Chi as our router.

Firstly, let's install Chi

go get -u github.com/go-chi/chi/v5
Enter fullscreen mode Exit fullscreen mode

Then, we'll define our main.go and start using Chi straight away. We're going to declare a new router and create an initial route to receive a GET request and then start our http server. That will look like this:

package main

import (
    "net/http"
    "github.com/go-chi/chi/v5"
)

func main() {
    router := chi.NewRouter()

    r.Get("/", testHandler)

    http.ListenAndServe(":8000", r)
}
Enter fullscreen mode Exit fullscreen mode

To recap this we're importing chi and net/http then defining a main function and creating a new Chi router and assigning it a new variable called router. We're then defining a new route at the path / that will receive a GET request and will run the testHandler function, we haven't defined that handler and we won't to keep this tutorial short. We then start the http server on port 8000 and pass the Chi router.

This has just touched the surface on Chi and it has a lot more features to offer when building an API and I plan to write more on the power of Chi in the future.

If you'd like to stay up to date with my content, make sure to follow me on Twitter

Oldest comments (0)