Plz yurn on JavaScript

Golang Rest API for NodeJS developer - Part 1

November 06, 20192 minutes to read

  • #nodejs
  • #tutorial
  • #golang
Subscribe

Golang Rest API for NodeJS developer - Part 1

In part 1, we will set up the foundation of our project. First, make sure you do have Go v1.13 install. On Mac, I recommend using Homebrew for that.

Go module init

First, create a folder where you will put the code for this project. Inside this folder run the command go mod init todo todo here will be the name of the project. In NodeJS we do npm init.

Setup the db connection

In this project, we will use the library go-pg so for that, we need to install it by running go get github.com/go-pg/pg. This will install the library and all the dependency. Coming from a NodeJS background this is the equivalent of npm install. Create a folder called postgres in the root of your project and a file with the same name with go as the extension.

In this file, we will create a function New where the only job of this one is returning a pointer to a DB instance

1// postgres/postgres.go
2
3package postgres
4
5import (
6 "github.com/go-pg/pg/v9"
7 _ "github.com/lib/pq"
8)
9
10func New(opts *pg.Options) *pg.DB {
11 db := pg.Connect(opts)
12
13 return db
14}

I like to keep the root of the package the same name as the folder, It's a convention I like to follow and make life easier

Setup the basic handlers/endpoint

Handlers will be like our controller ish stuff. This will be where the logic of the app are bound with the client, in this case, rest API. We will also set up middlewares and bind them to the router instance. For the routing, we use Chi and we can install it with go get github.com/go-chi/chi. I found Chi to be the best routing library in Go. The reason is first for me to look like Express who is the routing library I use each time in NodeJS. Also, this library follows the signature of the standard library. And in the Go community this is something they want.

1// handlers/handlers.go
2
3package handlers
4
5import (
6 "time"
7
8 "github.com/go-chi/chi"
9 "github.com/go-chi/chi/middleware"
10)
11
12type Server struct {
13
14}
15
16func setupMiddleware(r *chi.Mux) {
17 r.Use(middleware.RequestID)
18 r.Use(middleware.RealIP)
19 r.Use(middleware.Compress(6, "application/json"))
20 r.Use(middleware.Logger)
21 r.Use(middleware.Recoverer)
22 r.Use(middleware.URLFormat)
23 r.Use(middleware.Timeout(60 * time.Second))
24}
25
26func NewServer() *Server {
27 return &Server{}
28}
29
30func SetupRouter() *chi.Mux {
31 server := NewServer()
32
33 r := chi.NewRouter()
34
35 setupMiddleware(r)
36
37 server.setupEndpoints(r)
38
39 return r
40}

After this, we want some base endpoint. For this part-1 we will make just the barebone of it.

1// handlers/endpoint.go
2
3package handlers
4
5import "github.com/go-chi/chi"
6
7func (s *Server) setupEndpoints(r *chi.Mux) {
8 r.Route("/api/v1", func(r chi.Router) {
9 r.Route("/users", func(r chi.Router) {
10
11 })
12 })
13}

Setup the Main function

In Go everything starts from the Main function. So in our, we will finally initialize the database plus the routing. We also gonna make sure the router is running on a certain port. We check if the env variables provide a PORT variables else we use 8081. This is the equivalent in NodeJS of

1const port = process.env.PORT || 8081;

So create a file main.go in the root of the project and this should look like this.

1// main.go
2
3package main
4
5import (
6 "fmt"
7 "log"
8 "net/http"
9 "os"
10
11 "github.com/go-pg/pg/v9"
12
13 "todo/handlers"
14 "todo/postgres"
15)
16
17func main() {
18 DB := postgres.New(&pg.Options{
19 User: "postgres",
20 Password: "postgres",
21 Database: "todo_dev",
22 })
23
24 defer DB.Close()
25
26 r := handlers.SetupRouter()
27
28 port := os.Getenv("PORT")
29 if port == "" {
30 port = "8081"
31 }
32
33 err := http.ListenAndServe(fmt.Sprintf(":%s", port), r)
34 if err != nil {
35 log.Fatalf("cannot start server %v", err)
36 }
37}

Conclusion

If you did like this tutorial don't forget to subscribe to my newsletter below. Also, the video link is at the top of the post. If you have any question don't hesitate to ask in the comment section below.

Code for this part

Happy Coding :)

Previous

Golang Rest API for NodeJS developer - Part 2

Next

Golang Rest API for NodeJS developer - Intro

Subscribe to the Newsletter

Receive notification when new article get posted

Comments