Search⌘ K

Our User Interface

Explore how to build a complete Go web server for a URL shortener application. Learn to implement HTTP handler functions to process input, serve HTML forms, and redirect short URLs. Understand the use of interfaces in Go for handling HTTP responses, and test your local server to ensure proper URL storage and redirection behavior.

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 by the ...