Appendix B - Project: redditnews for Baby Gophers

baby-gopher
I am keen to be abreast with what’s happening in the Golang world. To that end, we will write a command-line program (redditnews.go) that fetches and displays the latest headlines from the golang page on Reddit.
The program will:
- make an HTTP request to the Reddit API.
- decode the JSON response into a Go data structure, and
- display each link’s author, score, URL and title.
We will then be building a bare-bones News Reader package (redditnews) that gives us the latest news and headlines from the Golang Sub-Reddit, using Reddit’s API.
Once the project is ready, we will use GMail to send an email which will contain the information fetched by the package redditnews.
Use GitHub
One of the best places to share your code with friends, co-workers, classmates, and complete strangers is GitHub1.
Create an account
On the main screen that shows up, enter your username, your email and create a password. Next, click on Sign up for GitHub. On the next screen, The ‘Free’ plan is automatically chosen for you. Just click on the Finish sign up button. You will receive an email asking you to ‘Confirm your email’. Please do that.
Set up Git
Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency.
If you are new to Git, then learn Git in 15 minutes2.
Next, Set Up Git3 on your computer as per the guide.
Complete Appendix A
I am assuming that you have completed Appendix A.
redditnews.go (First Iteration)
This is the first draft of my program.
In your browser, open the site http://reddit.com/r/golang.json4 the browser output is a huge blob of JSON that we receive from the Golang Subreddit. This may be difficult to look at in the browser, unless you have the JSONView plugin installed. These extensions are available for Firefox5 and Chrome. With the extension installed, here’s a partial view of the JSON:

JSON
Now let’s write the first draft of our program.
Make a new folder and cd to it as follows:
$ mkdir $GOPATH/src/github.com/SatishTalim/redditnews
$ cd $GOPATH/src/github.com/SatishTalim/redditnews
In this folder, create a file named redditnews.go, open it in your favorite editor, and add the following lines:
Program redditnews.go
package main
import (
"io"
"log"
"net/http"
"os"
)
func main() {
resp, err := http.Get("http://reddit.com/r/golang.json")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Fatal(resp.Status)
}
_, err = io.Copy(os.Stdout, resp.Body)
if err != nil {
log.Fatal(err)
}
}
- Like all Go programs that need to be executed, our program has a package
main. - Package io6 provides basic interfaces to I/O primitives.
- On an error we use log7. 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
log.Fatalfunction prints the error message and exits the program. - For web related http functionality, we import the package net/http8. Any functions within that we refer as
http.function_name. - Package os9 provides a platform-independent interface to operating system functionality.
- In our
main()function, we are setting a variablerespand doing aGETrequest to the Reddit API on our chosen Subreddit. - The
func Get(url string) (resp *Response, err error)issues a GET to the specified URL. Whenerrisnil,respalways contains a non-nilresp.Body. Caller should closeresp.Bodywhen done reading from it. Therespis of type Response10. - We use the
deferfunction to clean up after the HTTP request, and this call will only be executed after the function returns. - In our Error Handling, check that the HTTP server returns a “200 OK” response. If not, bail, printing the HTTP status message (“500 Internal Server Error”, for example).
- The package
net/httpdefines many constants11. - _ is a blank identifier which can be used when we don’t care about a particular return value.
- Finally, we copy the
resp.Body(filled with the JSON received from the Reddit API) to theos.Stdout. Theresp.Bodytype implementsio.Readerandos.Stdoutimplementsio.Writer.
Now you can run the program with the go tool:
$ cd $GOPATH/src/github.com/SatishTalim/redditnews
$ go run redditnews.go
When you run the program we are outputting (through os.Stdout) a huge blob of JSON that we received from the Golang Subreddit. Although we can actually see the Articles inside there, this is no good to us. We want to receive the Article’s Title, Author’s name, a Link to the Article, and we want to assess the value of the article, based on the Reddit link Score the Article has received.
- https://github.com/↩
- https://try.github.io/levels/1/challenges/1↩
- https://help.github.com/articles/set-up-git↩
- http://reddit.com/r/golang.json↩
- https://addons.mozilla.org/en-us/firefox/addon/jsonview/↩
- http://golang.org/pkg/io/↩
- http://golang.org/pkg/log/↩
- http://golang.org/pkg/net/http/↩
- http://golang.org/pkg/os/↩
- http://golang.org/pkg/net/http/#Response↩
- http://golang.org/pkg/net/http/#pkg-constants↩