A "hello world" web server with Chi
A "hello world" web server with Chi#
The standard library is great for building simple HTTP servers. But if you want to add complex routing logic, we recommend the Chi library. It adds a bunch of great functions, and a router, that all use the standard library.
A router or mulitplexer is included by default in Go, it's called
http.ServeMux and if you don't declare a router,
http.DefaultServeMux is used by default. While Go's
http.ServeMux is great, it doesn't allow two common types of request pattern matching: HTTP Method and variables. Chi adds these and a bunch of other things. Let's update our
server.go file to contain the following code instead of what we originally wrote before:
Some changes to this code block from the first. We have added a simple if statement to get the port to run on from an environment variable called
PORT. Next we have
r := chi.NewRouter(). The reason we are using Chi is to get a Router.
r is an instance of Chi's router, which will receive every HTTP request to the server. The line
log.Fatal(http.ListenAndServe(":"+port, r)) sets up our server to listen on the port we defined, and send everything to the router we created. It logs any errors and exits if the server returns anything.
We use the Chi Router for two reasons. The first is that it is compatible with the Go standard library package
net/http. There are a bunch of HTTP frameworks out there, but all of the easiest-to-use ones integrate with
net/http, because it provides so much for free. Another router that supports
net/http is Gorilla's Mux.
If you write code that works with
net/http, like Chi does, you can switch between frameworks easily depending on what features you need. You also have a consistent API for people writing middleware or handlers for you. For example, all of Chi's router functions take a function with definition
func(w http.ResponseWriter, r *http.Request), which is the exact same as