Go’s libraries makes it easy to write a web server that responds to client
requests like those made by fetch
.
In this section, we’ll show a minimal server that
returns the path component of the URL used to access the server.
That is, if the request is for http://localhost:8000/hello
, the
response will be URL.Path = "/hello"
.
// Server1 is a minimal "echo" server. package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", handler) // each request calls handler log.Fatal(http.ListenAndServe("localhost:8000", nil)) } // handler echoes the Path component of the requested URL. func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "URL.Path = %q ", r.URL.Path) }
The program is only a handful of lines long because library functions do
most of the work.
The main
function connects a handler function to incoming URLs whose path begins with /
, which is all URLs, and starts a server listening
for incoming requests on port 8000.
A request is represented as a struct of type http.Request
,
which contains a number of related fields, one of which is the URL of
the incoming request.
When a request arrives, it is given to the handler function, which
extracts the path component (/hello
) from the request URL and
sends it back as the response, using fmt.Fprintf
.
Web servers will be explained in detail in
Section 7.7.
Let’s start the server in the background.
On Mac OS X or Linux, add an ampersand (&
) to the command;
on Microsoft Windows, you will need to run the command without the
ampersand in a separate command window.
$ go run src/gopl.io/ch1/server1/main.go &
We can then make client requests from the command line:
$ go build gopl.io/ch1/fetch $ ./fetch http://localhost:8000 URL.Path = "/" $ ./fetch http://localhost:8000/help URL.Path = "/help"
Alternatively, we can access the server from a web browser, as shown in Figure 1.2.
It’s easy to add features to the server. One useful addition
is a specific URL that returns a status of some
sort. For example, this version does the same echo but also counts
the number of requests; a request to the URL /count
returns
the count so far, excluding /count
requests themselves:
// Server2 is a minimal "echo" and counter server. package main import ( "fmt" "log" "net/http" "sync" ) var mu sync.Mutex var count int func main() { http.HandleFunc("/", handler) http.HandleFunc("/count", counter) log.Fatal(http.ListenAndServe("localhost:8000", nil)) } // handler echoes the Path component of the requested URL. func handler(w http.ResponseWriter, r *http.Request) { mu.Lock() count++ mu.Unlock() fmt.Fprintf(w, "URL.Path = %q ", r.URL.Path) } // counter echoes the number of calls so far. func counter(w http.ResponseWriter, r *http.Request) { mu.Lock() fmt.Fprintf(w, "Count %d ", count) mu.Unlock() }
The server has two handlers, and the request URL determines which one is
called: a request for /count
invokes counter
and all others invoke
handler
. A handler pattern that ends with a slash matches any URL that
has the pattern as a prefix.
Behind the scenes, the server runs the handler for each incoming
request in a separate goroutine so that it can serve multiple
requests simultaneously.
However, if two concurrent requests try to update
count
at the same time, it might not be incremented consistently; the program
would have a serious bug called a
race condition (§9.1).
To avoid this problem, we must ensure that at most one goroutine accesses
the variable at a time, which is the purpose of the mu.Lock()
and mu.Unlock()
calls that bracket each access of count
.
We’ll look more closely at concurrency with shared variables in
Chapter 9.
As a richer example, the handler function can report on the headers and form data that it receives, making the server useful for inspecting and debugging requests:
// handler echoes the HTTP request. func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "%s %s %s ", r.Method, r.URL, r.Proto) for k, v := range r.Header { fmt.Fprintf(w, "Header[%q] = %q ", k, v) } fmt.Fprintf(w, "Host = %q ", r.Host) fmt.Fprintf(w, "RemoteAddr = %q ", r.RemoteAddr) if err := r.ParseForm(); err != nil { log.Print(err) } for k, v := range r.Form { fmt.Fprintf(w, "Form[%q] = %q ", k, v) } }
This uses the fields of the http.Request
struct
to produce output like this:
GET /?q=query HTTP/1.1 Header["Accept-Encoding"] = ["gzip, deflate, sdch"] Header["Accept-Language"] = ["en-US,en;q=0.8"] Header["Connection"] = ["keep-alive"] Header["Accept"] = ["text/html,application/xhtml+xml,application/xml;..."] Header["User-Agent"] = ["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)..."] Host = "localhost:8000" RemoteAddr = "127.0.0.1:59911" Form["q"] = ["query"]
Notice how the call to ParseForm
is nested within an if
statement.
Go allows a simple statement such as a local variable declaration to
precede the if
condition, which is particularly useful for
error handling as in this example.
We could have written it as
err := r.ParseForm() if err != nil { log.Print(err) }
but combining the statements is shorter and reduces the scope of the
variable err
, which is good practice.
We’ll define scope in Section 2.7.
In these programs, we’ve seen three very different types used as output
streams. The fetch
program copied HTTP response data
to os.Stdout
, a file, as did the lissajous
program. The fetchall
program threw the response away (while counting its length) by
copying it to the trivial sink ioutil.Discard
.
And the web server above used
fmt.Fprintf
to write to an http.ResponseWriter
representing the web browser.
Although these three types differ in the details of what they do, they all satisfy a
common interface, allowing any of them to be used wherever an output
stream is needed.
That interface, called io.Writer
, is discussed in
Section 7.1.
Go’s interface mechanism is the topic of
Chapter 7, but to give an idea of what
it’s capable of, let’s see how easy it is to combine the web server
with the lissajous
function so that animated GIFs
are written not to the standard output, but to the HTTP client.
Just add these lines to the web server:
handler := func(w http.ResponseWriter, r *http.Request) { lissajous(w) } http.HandleFunc("/", handler)
or equivalently:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { lissajous(w) })
The second argument to the HandleFunc
function call immediately above
is a function literal, that is, an anonymous function defined at its
point of use.
We will explain it further in Section 5.6.
Once you’ve made this change, visit http://localhost:8000
in
your browser.
Each time you load the page, you’ll see a new animation like the one
in Figure 1.3.
Exercise 1.12:
Modify the Lissajous server to read parameter values from the URL.
For example, you might arrange it so that a URL like
http://localhost:8000/?cycles=20
sets the number of cycles to 20 instead of the default 5.
Use the strconv.Atoi
function to convert the string
parameter into an integer.
You can see its documentation with go doc strconv.Atoi
.
3.238.228.237