Photo by Florian Olivo on Unsplash

Backend Development with Go Part 2

Jonathan Reeves
3 min readSep 22, 2021

--

Hello and welcome back to the second part of this series. As I mentioned in the first one, I will be documenting my journey of using Go as a backend language instead of my usual language/framework of Node and Express.

So far the journey is me diving through some material for learning how the net/http package in Go works. I have found it to be a really great package for easily creating a web server. Below is a snippet of code used to create a basic server:

package mainimport (
"fmt"
"net/http"
)
func handler(writer http.ResponseWriter, request *http.Request) {
fmt.Fprintf(writer, "Hello World, %s!", request.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}

The above code creates a web server listening on port 8080. When you open up a browser, or in my case Postman, to localhost:8080 you will be greeted with the below:

Postman screenshot of the response from the root route

And if you were to instead add something like this to the route: localhost8080/hello/from/Go

You would see:

Postman screenshot of the response from localhost:8080/hello/from/go

Using the net/http package really makes it a simple process for creating a server. Going back to the code you set up a handler function which takes two parameters a ResponseWriter which in this case we called writer and a pointer to http.Request which we named request. Inside of that function we use the fmt package to format our print method which takes our writer param, a string message, and then the request param with the URL Path slice which is optional to print out the responses above in the Postman screenshots. We then create a main function. Just like in Java or C# you have to have a main function be the root of your application. So below is our main function which calls two http methods. The first one handles the function call for our handler function which sets the route to “/”. The next method calls the ListenAndServe method which just like it reads both listens and serves our web server on the port we specify of 8080 and takes a nil parameter for the second optional param.

Conclusion

This was my first step into the long road ahead of using Go for backend development. I hope that this short article has shown you, in a small but efficient program, the power of the Go language for backend use. I am enjoying the language so far.

--

--

Jonathan Reeves

I am a software engineer that is currently trying to break into the DevOps world using Python. Professionally I use JavaScript with React to build websites.