Golang Rest API for NodeJS developer - Part 1
November 06, 2019 • 2 minutes to read
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.go23package postgres45import (6 "github.com/go-pg/pg/v9"7 _ "github.com/lib/pq"8)910func New(opts *pg.Options) *pg.DB {11 db := pg.Connect(opts)1213 return db14}
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.go23package handlers45import (6 "time"78 "github.com/go-chi/chi"9 "github.com/go-chi/chi/middleware"10)1112type Server struct {1314}1516func 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}2526func NewServer() *Server {27 return &Server{}28}2930func SetupRouter() *chi.Mux {31 server := NewServer()3233 r := chi.NewRouter()3435 setupMiddleware(r)3637 server.setupEndpoints(r)3839 return r40}
After this, we want some base endpoint. For this part-1 we will make just the barebone of it.
1// handlers/endpoint.go23package handlers45import "github.com/go-chi/chi"67func (s *Server) setupEndpoints(r *chi.Mux) {8 r.Route("/api/v1", func(r chi.Router) {9 r.Route("/users", func(r chi.Router) {1011 })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.go23package main45import (6 "fmt"7 "log"8 "net/http"9 "os"1011 "github.com/go-pg/pg/v9"1213 "todo/handlers"14 "todo/postgres"15)1617func main() {18 DB := postgres.New(&pg.Options{19 User: "postgres",20 Password: "postgres",21 Database: "todo_dev",22 })2324 defer DB.Close()2526 r := handlers.SetupRouter()2728 port := os.Getenv("PORT")29 if port == "" {30 port = "8081"31 }3233 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.
Happy Coding :)