...

/

Our User Interface

Our User Interface

This lesson shows the implementation of the application by designing a server and making a front end to see how things work.

Designing a server

We haven’t yet coded the function with which our program must be started. This is (always) the function main() as in C, C++ or Java. In it, we will start our web server, e.g., we can start a local web server on port 8080 with the command:

http.ListenAndServe(":8080", nil)

The web server listens for incoming requests in an infinite loop, but we must also define how this server responds to these requests. We do this by making so-called HTTP handlers with the function HandleFunc. For example, by coding http.HandleFunc("/add", Add) we say that every request which ends in /add will call a function Add (still to be made).

Our program will have two HTTP handlers:

  • Redirect, which redirects short URL requests
  • Add, which handles the submission of new URLs

Schematically:

Our minimal main() could look like:

func main() {
  http.HandleFunc("/", Redirect)
  http.HandleFunc("/add", Add)
  http.ListenAndServe(":8080", nil)
}

Requests to /add will be served by the Add handler, where all the other requests will be served ...