Skip to content

The main.go File

Filename Location Group Project/Repository
main.go ./main.go application httpcats

Why?

We need an application to deliver some static content for us, and this is it. In the future it will do more for us but in the mean time this is all we need it to do.

Breakdown

As we can see from the below lines, all we're telling the HTTP server to do is use the ./static directory for locating static files that are requested and then serve them on /*:

1
2
    fs := http.FileServer(http.Dir("./static"))
    http.Handle("/", fs)

We're creating a handler function in fs and then attaching it to the / request path (so we're capturing everything, essentially). This means any requests for /, /image.png, /index.html, etc, will be routed to the handler function is the fs variable.

All we're doing after this is telling Go to serve our handler functions on port 8080:

1
    err := http.ListenAndServe("0.0.0.0:8080", nil)

Simple.

The Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
    "log"
    "net/http"
)

func main() {
    fs := http.FileServer(http.Dir("./static"))
    http.Handle("/", fs)

    log.Println("Listening on 0.0.0.0:8080")
    err := http.ListenAndServe("0.0.0.0:8080", nil)
    if err != nil {
        log.Fatal(err)
    }
}

Committing the Code

  1. Set your working directory to the application/httpcats repository
  2. Save the file and use git add main.go to add it to the Git staging area
  3. Use git commit -am 'creating our main application file' to commit the file to our repository
  4. Push the code to GitLab.com: git push -u origin master

Running the Code

  1. Set your working directory to the application/httpcats repository
  2. Use go run . to have the Go compiler compile the code and run the binary

You should see output like this (given a few seconds for the first compile):

1
2
$ go run .
2021/07/01 21:29:16 Listening on 0.0.0.0:8000

Last update: August 25, 2021