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 ashttp.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
mainprogram, we redirect any incoming requests to thehandlerfunction. We do this by callinghttp.HandleFuncand 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 functionGetPortwhich internally callsGetenv(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
logimplements a simple logging package. It defines a type,Logger, with methods for formatting output. It also has a predefined ‘standard’ Logger accessible through helper functionsPrint[f|ln],Fatal[f|ln], andPanic[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
handleris of the typehttp.HandlerFunc. It takes anhttp.ResponseWriterand anhttp.Requestas its arguments. - when a user connects, the program responds with a text that is sent back to the browser. The
http.ResponseWritervalue assembles the HTTP server’s response; by writing to it, we send data to the HTTP client. - an
http.Requestis a data structure that represents the client HTTP request. - all the parameters of a request can be received via the parameter
http.Requestin thehandler. 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 18Write a Go web program called |
|
Exercise 19Write 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
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
- http://golang.org/pkg/fmt/↩
- http://golang.org/pkg/net/http/↩
- http://golang.org/pkg/os/↩
- http://golang.org/pkg/log/↩
- http://localhost:4747↩
- https://developers.google.com/maps/documentation/geocoding/↩
- https://developers.google.com/maps/documentation/streetview/index↩
- http://creativecommons.org/licenses/by-nc-sa/3.0/↩