Appendix B - Build, deploy webapps to cloud

Complete Appendix A

I am assuming that you have completed Appendix A.

A basic Go web app

Our objective here is to build a web app in Go. In the following program, we shall start a simple service on our local machine. We will have the program running on some port number. When you access the local machine at http://localhost:port_no (which is the same as http://127.0.0.1:port_no), it will print a text message on the screen.

Make a new folder and cd to it as follows:

1 $ mkdir $GOPATH/src/github.com/SatishTalim/webapp
2 $ cd $GOPATH/src/github.com/SatishTalim/webapp

Note: Replace SatishTalim with your GitHub name.

In this folder, create a file named webapp.go, open it in your favorite editor, and add the following lines:

Program webapp.go


 1 package main
 2 
 3 import (
 4 	"fmt"
 5 	"log"
 6 	"net/http"
 7 	"os"
 8 )
 9 
10 func main() {
11 	http.HandleFunc("/", handler)
12 
13 	err := http.ListenAndServe(GetPort(), nil)
14 	if err != nil {
15 		log.Fatal("ListenAndServe: ", err)
16 	}
17 }
18 
19 func handler(w http.ResponseWriter, r *http.Request) {
20 	fmt.Fprintf(w, "Hello. This is our first Go web program!")
21 }
22 
23 // Get the Port from the environment so we can run on Heroku
24 func GetPort() string {
25 	var port = os.Getenv("PORT")
26 	// Set a default port if there is nothing in the environment
27 	if port == "" {
28 		port = "4747"
29 		fmt.Println("INFO: No PORT environment variable detected, defaulting to " + port)
30 	}
31 	return ":" + port
32 }

  • like all Go programs that need to be executed, our program has a package main.
  • we import the fmt1 and net/http2 packages from the Go standard library.
  • to work with some printing functions, we import the package fmt.
  • package os3 provides a platform-independent interface to operating system functionality.
  • for web related http functionality, we import the package http. Any functions within that we refer as http.function_name.
  • the first thing we need to do is tell our server what to do when someone comes to our homepage. So, we need to have a request handler at root (“/”). Within the main program, we redirect any incoming requests to the handler function. We do this by calling http.HandleFunc and passing it two parameters - the first one is a part of the incoming url, and the second is the method capable of handling it.
  • it then calls http.ListenAndServe, specifying that it should listen on port returned by our local function GetPort which internally calls Getenv (retrieves the value of the environment variable named by the key. It returns the value, which will be empty if the variable is not present) on any interface. (Don’t worry about its second parameter, nil, for now.) This function will block until the program is terminated.
  • on an error we use log4. Package log implements a simple logging package. It defines a type, Logger, with methods for formatting output. It also has a predefined ‘standard’ Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and Panic[f|ln], which are easier to use than creating a Logger manually. That logger writes to standard error and prints the date and time of each logged message.
  • the function handler is of the type http.HandlerFunc. It takes an http.ResponseWriter and an http.Request as its arguments.
  • when a user connects, the program responds with a text that is sent back to the browser. The http.ResponseWriter value assembles the HTTP server’s response; by writing to it, we send data to the HTTP client.
  • an http.Request is a data structure that represents the client HTTP request.
  • all the parameters of a request can be received via the parameter http.Request in the handler. You can get the URL, the input values and other details.

Now you can build and install that program with the go tool:

$ cd $GOPATH/src/github.com/SatishTalim/webapp
$ go install

You can now run the program by typing:

$ webapp
listening...
INFO: No PORT environment variable detected, defaulting to 4747

If you run this program and access the URL: http://localhost:47475 the program would present a page containing:

Hello. This is our first Go web program!

Great, it worked!

Exercise 18

Write a Go web program called webtime.go in the folder $GOPATH/src/github.com/YourGithubName/webtime such that when the user accesses the URL: http://localhost:4747 the program would present a page containing: The current time here is 2013-09-22 09:47:28.568023 +0530 IST. Note that the time shown by the server you write would be different than what’s shown here.

Exercise 19

Write a Go program that displays the street view photo of a given address. Use the Google Geocoding API6 which we had used earlier in the JSON chapter. Also, use the Google Street View Image API7 to display the street view photo for a given address. For the address say “1600 Pennsylvania Avenue Northwest, Washington, DC 20500, United States” the photo to be displayed in your browser is as shown below.

White House

White House

The address used in the exercise above is that of a landmark, historic home and office of the United States president.

Exercise 18 Solution:

Exercise 19 Solution:

License

This work is licensed under the Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a copy of this license, visit here8.

All example code used in this book is hereby put in the public domain.

©Satish Talim - 2015

  1. http://golang.org/pkg/fmt/
  2. http://golang.org/pkg/net/http/
  3. http://golang.org/pkg/os/
  4. http://golang.org/pkg/log/
  5. http://localhost:4747
  6. https://developers.google.com/maps/documentation/geocoding/
  7. https://developers.google.com/maps/documentation/streetview/index
  8. http://creativecommons.org/licenses/by-nc-sa/3.0/