Go: HTTP server example
If you run the program below and access the URL http://localhost:8080/world, you will be greated by this page:

package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", HelloServer)
http.ListenAndServe(":8080", nil)
}
func HelloServer(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
}
- The call to
http.HandleFunctells thenet.httppackage to handle all requests to the web root withHelloServer. - The call to
http.ListenAndServetells the server to listen on the TCP network address:8080. This function blocks until the program is terminated. - Writing to an
http.ResponseWritersends data to the HTTP client. - An
http.Requestis a data structure that represents a client HTTP request. r.URL.Pathis the path component of the request URL; the path component ofhttp://localhost:8080/worldis/world.
Further reading
The Writing Web Applications tutorial shows how to extend this small example into a complete wiki.
The tutorial covers how to:
- create a data structure with load and save methods,
- use the
net/httppackage to build web applications, - use the
html/templatepackage to process HTML templates, - use the
regexppackage to validate user input.
Comments
Be the first to comment!