Tuesday, October 4, 2022

Starting Out on the go-chi Framework Example

Picture this. The company you work for has decided to move from Java to Golang to create microservices. What would you do? As for me, I went straight into creating an HTTP GET endpoint that returns a nice "hello world" message. As you'll see below, the code uses the go chi framework. Why the go-chi framework? I don't really know but maybe because it was recommended by the long time IT provider of the company. Based on the quickstart examples, the Gin Web framework seemed easier to understand.

First of all, I will not be talking about setup and installation of Go. I am assuming that the reader has sufficient knowledge in setting up Go. I'm on Windows 10 using Visual Studio Code along with it's Go extensions to edit my code. I'd recommend running go install github.com/go-delve/delve/cmd/dlv@latest on the command line so that you can do "Run and Debug" in VS Code.

Baby Steps

  1. Create a go-chi-hello directory and go in.
  2. Execute go mod init go-chi-hello on the command line. This will create a go.mod file in the current directory.
  3. Create main.go. Copy the contents from below.
  4. Execute go mod tidy on the command line. This will update go.mod, adding the dependencies.
  5. Execute go run main.go on the command line. Hit the endpoint using a browser, Postman or whatever you like.

main.go


package main

import (
	"net/http"

	"github.com/go-chi/chi/middleware"
	"github.com/go-chi/chi/v5"
)

func main() {
	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte("{ \"message\": \"Hello World!\" }"))
	})
	http.ListenAndServe(":3000", r)
}

Pretty simple program. An HTTP GET request triggers a response of "Hello World!" in JSON format. The server is listening on port 3000.

You should see something like below when a request comes if you have the logger set.


2022/10/04 15:27:43 "GET http://localhost:3000/ HTTP/1.1" from 127.0.0.1:56005 - 200 29B in 0s
2022/10/04 15:27:45 "GET http://localhost:3000/ HTTP/1.1" from 127.0.0.1:56005 - 200 29B in 0s

On Firefox developer, you should see something like below if the content type is set to JSON otherwise you'll see the other one.  

go-chi JSON Response


 
go-chi Plaintext Response

There you have it. The simplest endpoint to start with. Next step would be to hook this up with Accessing MySQL using Go Example.