Skip to content

Lesson 1: Hello, world!

vcgalpin edited this page Nov 24, 2020 · 8 revisions

Let's start with the simplest possible program: one that just prints "Hello, world" (albeit on a Web page):

fun mainPage (_) {
  page 
    <html>
    <body>
    <h1>Hello world!</h1>
    </body>
    </html>
}

fun main () {
  addRoute("",mainPage);
  servePages()
}

main()

This is a tiny bit more complicated than you might expect. Let's go through the main components of the program:

The mainPage function defines what to do to render the main page of the program. The keyword fun starts a function definition, and we write (_) to indicate that there is one argument but that we don't care about its value. (The underscore _ is a wildcard that can be used as a variable if we don't care about the variable's value.) The body of the function is enclosed in curly braces.

The body of the function defines the return value. In Links, the body of a function is evaluated to a value, which is returned. In this case, the return value is a page, defined using the page keyword. Pages can be defined using XML literals; for example, here we write <html> and <body> tags, then <h1>Hello world!</h1>, then the appropriate closing tags. The difference between a page and an XML value is that a page has additional structure needed for Links to render the page as the result of a web request (for example to handle any forms embedded in the page).

The main function calls addRoute to install the mainPage handler as the default response to any HTTP request, and servePages() starts the Links web server.

To run this example, type the following (from within directory 1_hello):

$ linx hello.links

The command should not return. If you followed the VM configuration instructions, you should be able to visit the web page at http://localhost:8081 from outside the VM.

Exercises

  1. Change the program by modifying the content of the HTML body, or adding content (such as a page title) under the <head> tag. Does this work? What happens if you add HTML with unbalanced tags, e.g. <p> test <b> bold </p>?

In Links, HTML or XML literals have to have balanced tags, even in cases where HTML would infer a closing tag.

  1. In Links, there is a difference between a page (which is a legitimate response to an HTTP request) and plain XML. What happens if you omit the keyword page from mainPage?

This results in a type error, since the second argument of addRoute should be a function that returns a Page, not Xml.

  1. If you are familiar with CSS or JavaScript, what happens if you include a <style> or <script> tag in the page content?

CSS content can be included in a <style> tag as usual. Including JavaScript is a little more problematic, since Links translates some of its own code to JavaScript and loads some JavaScript libraries. In general it is best to avoid including JavaScript code in your Links program unless you know what you are doing.