CSS 390: Notes from Lecture 2 (DRAFT)

Our Story So Far

What is Software Engineering?

What is Tactical (vs. Strategic)

Goals & Non-Goals

Goals

Non-Goals

Important points of implementation incidental to or outside the scope of the course:

Why Go?

Introduction to Go

It's All About that Code

Simple makefile so you don't have to remember to reset your environment variables (ymmv):

PACKAGES=...
TEST_PACKAGES=...

GOPATH=$(CURDIR)
GODOC_PORT=:6060

all: fmt install

install:
	GOPATH=$(GOPATH) go install $(PACKAGES)

test:
	#GOPATH=$(GOPATH) go test $(TEST_PACKAGES)

fmt:
	GOPATH=$(GOPATH) go fmt $(PACKAGES)

doc:
	GOPATH=$(GOPATH) godoc -v --http=$(GODOC_PORT) --index=true

clean:

Your basic hello world program (with a couple of in-class additions): easily readable by anyone who never saw even a single line of Go code.

// Hello is the standard hello world program.
// The documentation requires no special formatting or markups.  Just
// write about the the thing you are documenting
//
// Odin and Zeus were here.
// Freyja and Hera were here.
package main

import (
	"fmt"
)

// main does the deed.
func main() {
	x := 2 * 4
	fmt.Printf("Hello, world!, %d\n", x)
}

Note how the godoc command, with the right flags, fires off a web server with documentation extracted from your source files seamlessly embedded into the standard library documentation. Also note how no special markup codes are required. Take some time to browse through the standard library documentation.

Web Server

You can create a simple web server in a couple of lines using the standard library. Note that functions are first class objects: wherever you could use the name of a function, you may use a function literal.

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func (response http.ResponseWriter, request *http.Request) {
		fmt.Fprintln(response, "<html>\n<body>\n<h1>Hello, Apollo!</h1></body>")})
	fmt.Printf("Server fail: %s\n",  http.ListenAndServe(":8080", nil))
}

Of course, not the most easily-read piece of code, so let us break it up a little, and avoid creating abusive function literals.

package main

import (
	"fmt"
	"net/http"
)

func hello (response http.ResponseWriter, request *http.Request) {
	fmt.Fprintln(response, "<html>")
	fmt.Fprintln(response, "<body>")
	fmt.Fprintln(response, "<h1>Hello, Apollo!</h1>")
	fmt.Fprintln(response, "</body>")
}

func main() {
	http.HandleFunc("/", hello)
	err := http.ListenAndServe(":8080", nil)
	fmt.Printf("Server fail: %s\n", err)
}

Note that the code calls fmt.Fprintln on a http.ResponseWriter object. Without getting into the details of Go's interface mechanism yet, fmt.Fprintln takes as the file parameter anything that implements the io.writer interface (from the io standard library package). A common Go pattern is to have small single-function interfaces named by appending "er" to the function name, so a Writer is any object that implements a Write method.

Footnotes