DEV Community

Cover image for From Node to Go | Part 1
Siddharth Udeniya
Siddharth Udeniya

Posted on • Edited on

From Node to Go | Part 1

Hi Reader! Welcome to the From Node to Go series.

This series is basically for all the Node.js developers who want to switch to or learn Golang. But since I am starting this from very very basics of Nodejs as well, this can be used to learn web dev in Node.js as well.

PRE-REQUISITE for this series: You should know how to run node and go programs and you know the basics of Go. If not, I would recommend doing a quick walk through here (Excellent stuff)

2 - in - 1 !! Oh Yeah!

END-GOAL of this series: Writing microservices in Go! with all the jargon like Auth, Async Communication, etc included.

In this part, we will be focusing on creating a simple HTTP server in Node (NO EXPRESS, just plain simple Node.js) and Golang.

So let's dive in.

Creating HTTP server in Nodejs is simple. You import the HTTP module and call createServer function. .listen tells you on which port you want your HTTP server to listen to.

var http = require('http');

http.createServer(function (req, res) {
  res.write('Hello World!'); 
  res.end(); 
}).listen(8080); 
Enter fullscreen mode Exit fullscreen mode

Now go to your browser and open http://localhost:8080/, you should be able to see the Hello World message there.

Now let's do the same thing in Golang.

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", HelloWorld)
    http.ListenAndServe(":8081", nil)
}

//HelloWorld Handler
func HelloWorld(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
}
Enter fullscreen mode Exit fullscreen mode

Run this go program and now go to your browser and open http://localhost:8081/, you should be able to see the Hello World message there.

We imported 2 packages:
fmt: Format I/O (For further reading: fmt package)
net/http: Importing HTTP package which is a sub-package inside net package (does all the networking stuff) (For further reading HTTP package)

Define a handler function for the particular route - We defined HelloWorld handler here.

In ListenAndServe function we passed the address and nil, we will discuss this nil in the next part of this series.

The HTTP Handler takes 2 arguments here

  • An object of type ResponseWriter which is an interface in Go (For further reading: ResponseWriter
  • A pointer to Request which is a struct in Golang (For further reading: Request)

You should probably be having this question in mind right now!

So that's it. That's how you create a plain simple HTTP server in Node and Golang. Stay tuned for the next parts.

Top comments (0)