Switch from NodeJS to Golang: Router & Post Request

How to build a web server in Go. We’re going to build a very simple api to demonstrate how easy it is to implement it in Golang. I would say most NodeJS developers are familiar with ExpressJS so we will use that framework style that we all know and love.

If you want to setup live-reload similar to nodemon part 1

Here is all the code we need to setup the Api to have the ExpressJS type router functionality and a Post Method.

First create your directory and enter into it. go mod init is similar to npm init -( tracks dependencies ) keep note of this we are initializing the folder name.

mkdir simple_post_request
cd simple_post_request
go mod init example.com/simple_post_request

Just like you do with NodeJS: create a server.go file. Add the following:
server.go

package main
import (
"fmt"
"net/http"
// this is the Router package
"github.com/gorilla/mux"
)// Router this initializes the Router
var Router = mux.NewRouter()
func main() {// port number
var port string = ":4000"
fmt.Println("http://localhost" + port)
Router.HandleFunc("/", MessagePost).Methods("POST")
http.ListenAndServe(port, Router)
}

At this point the IDE you using might scream at you because you havent downloaded gorilla/mux to do that we simply:

go get -u github.com/gorilla/mux

gorilla/mux is our router for golang. Its just like ExpressJS for NodeJS. I'm not gonna go over what “net/http” is cause it's just a standard library that come with golang.

Now create a post request method
postRequest.go

package main
import (
"encoding/json"
"net/http"
)
// Method: POSTfunc MessagePost(write http.ResponseWriter, req *http.Request) {// We need to use to use the struct model to map the json data totype Message struct {
Name string `json:"name"`
Msg string `json:"msg"`
}
var jsonResponse Message// We decode the incoming data and convert it to a json
json.NewDecoder(req.Body).Decode(&jsonResponse)
// Send a success message back to client
json.NewEncoder(write).Encode("post sent Successfully")
}

Here we had to import “encoding/json” in order to handle Json. It's in the standard package so no biggie. Keep know that I capitalized the function MessagePost as this is how you export functions.

The only complicated thing or new thing here is struct’s. We don't have it in JavaScript. So it makes things a tiny bit more complicated. But we are not going into that I want to keep this short.

Let run it. Make sure your in the same directory as your project.

go run . 

If all is well it should compile and be running on localhost port 4000.
Open a Postman or whatever you use for testing APIs.
Example:

Well there you go we kept it short and sweet.

“Genius” is 1% inspiration and 99% perspiration. Accordingly, a ‘genius’ is often merely a talented person who has done all of his homework — T.E.