Go programming // Part 2 — Web Server

Creating a web server to generate QR codes

This article is part of the She Hacks Academy (a hackathon training program for women, by women) where we write about different topics that might help other women participate and thrive in hackathons.

I’ve always liked learning how to build things by actually building things.
In part 2 of this series on learning the go programming language we are going to create a web server using an example from golang.org. This will be used to generate QR codes for a URL using the Google Chart API. I really love this example because you can learn a ton and build something you can use in a few minutes. If you aren’t sure what an API is you should totally check out the She Hacks “What is an API” post.

First start by opening up ATOM and creating a file called webserver.go with the following code:

Build a go web server!

The code is available on GitHub over here.

When you open up terminal and run your app, you will then start your web server over at http://localhost:1718 .

Start your web server

If you then open up your web browser and visit http://localhost:1718 you will see that you app is up and running!

Yay it’s running!

If you click Show QR, you will then generate a QR code!

Scan the QR code to load the URL

You can now use a QR reader app on your phone to scan the QR code. It will then load the url that you entered.

So now let’s have a deeper look at the code to understand what you have created. First you need to create a package called main and import the necessary packages that you will use for the app. We are using flag, html/template, log and net/http for the web server app.

Next you will need to create two variables, one to set a default HTTP port for our server called addr and one for the html template called templ. The templ variable creates a new html template called qr using the templateStr that you will set later.

The main function is up next, it parses the flags and binds the function QR to the root path for the server. We then call http.ListenAndServe to start the server.

The QR function receives the request and executes the template.

We finish off with the HTML template, it’s a piece of HTML text created on the fly by substituting elements derived from items passed to templ.

When a URL has not yet been entered on the page, the piece from {{if .}} to {{end}} will not execute. The two snippets {{.}} are used to display the returned QR code from the Google Chart API.

The rest of the template is used to display the form to accept and submit the URL. This URL is then used to generate the QR code.

And that’s all you need to do! A simple example of a cool app that you can build super quickly to try out Go! ❤