In our last installment, we learned how to pass in flags to our command line application using the flag library. This time around we are going build a simple, executable Hello World HTTP server. Here is the full program:
package main
import "flag"
import "fmt"
import "net/http"
import "net/url"
import "strings"
var port int
func init() {
flag.IntVar(&port, "port", 8080, "port to run the server on")
flag.Parse()
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %sn", name(r.URL))
}
func main() {
http.HandleFunc("/hello/", handler)
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
func name(u *url.URL) string {
pathParts := strings.Split(u.String(), "/")
return pathParts[len(pathParts)-1]
}
Some new things to note here:
1) An init() function that runs before main() gets run that we are using to set up our command line flags.
2) A handler() function. We map this function as the function to run when someone navigates to a path like “/hello/mike”. The http.HandleFunc() call wires this together for us.
3) The call to http.ListenAndServe() that starts the server. This call will block as requests come into the server. You can kill the server with ctrl-c.
4) A private helper function name() that parses the URL to get the name. It makes use of strings.Split() and slices to do it’s work.
The thing that amazed me with this example is how easy it is to get an HTTP server up and running with Go. Granted it doesn’t do much yet but it has all of the moving parts to be able to serve up responses.
I hope that these first three installments have gotten you excited to learn some Go. The Go team has done a great job of providing a lot of good documentation for Go. Coupled with the simplicity of the language, you shouldn’t have any trouble getting up to speed quickly. When I start on the CloudFoundry Logging team on Monday, I will write about all of the ups and downs we have implementing a production ready system using Go.
Until then, use the following resources (in the order I read them) to get up to speed as we ramp up the density of the code going forward. You can use http://play.golang.org/ to play with Go as you learn.
1) Tour of Go
2) Effective Go
Some good reference material as you write more Go: