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:

Web browser localhost:8080

package main

import (

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.HandleFunc tells the net.http package to handle all requests to the web root with HelloServer.
  • The call to http.ListenAndServe tells the server to listen on the TCP network address :8080.
    This function blocks until the program is terminated.
  • Writing to an http.ResponseWriter sends data to the HTTP client.
  • An http.Request is a data structure that represents a client HTTP request.
  • r.URL.Path is the path component of the request URL;
    the path component of http://localhost:8080/world is /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/http package to build web applications,
  • use the html/template package to process HTML templates,
  • use the regexp package to validate user input.


Be the first to comment!