Writing a Simple Web Application

This lesson provides a program, and detailed description to design a web application, printing response in the form of HTML.

We'll cover the following

A web application

In the following program from line 7 to line 10, we see how the HTML, needed for our web form (which is a simple input form with text box and submit button) is stored in a multi-line string constant form.

The program starts a webserver on port 3000 at line 39. It uses a combined if statement so that, whenever an error occurs, the web server stops with a panic statement (see line 40). Before starting a webserver, we see two so-called routing statements:

  • http.HandleFunc("/test1", SimpleServer) at line 37
  • http.HandleFunc("/test2", FormServer) at line 38

This means that whenever the URL ends with /test1, the webserver will execute the function SimpleServer, and the same for /test2 with FormServer.

Now, look at the header of SimpleServer() at line 13. It outputs a hello world string in the browser by writing the corresponding HTML string to io with the WriteString method at line 14.

Now, look at the header of FormServer() at line 19. The browser can request _two different HTML methods: GET and POST. The code for FormServer uses a switch (starting at line 22) to distinguish between the 2 possibilities. If this URL is requested by the browser initially, then the request has a GET method, and the response is the constant form, as stated at line 25. When entering something in the text box and clicking the button, a POST request is issued. In the POST case, the content of the text box with a name in it is retrieved with the request.FormValue("in"), as you can see at line 32, and written back to the browser page.

Start the program in a console and open a browser with the URL https://1dkne4jl5mmmm.educative.run/test2 ( in your case the URL will be different) to test this program:

Remark: Change line 39 to if err := http.ListenAndServe(":8088", nil); err != nil { if you’re running the server locally.

Get hands-on with 1400+ tech skills courses.