Go: serving static files

Go: serving static files

In this article, we'll explore how to serve static files via HTTP in Go using the language's standard library.

Go is an open-source programming language developed by Google that is gaining popularity for developing web and server applications. In this article, well explore how to serve static files via HTTP in Go using the languages standard library.

Before we get into the process of serving static files, its important to understand what is meant by "static files" in a web context. Static files are files that dont dynamically change based on user requests. These include files such as HTML, CSS, JavaScript, images, fonts and other assets needed for a web page to display properly.

We create a new folder for our project and inside it we create the main file main.go in which we will write the code for the server.

To get started, lets open the main.go file and import Gos standard library:


package main

import (
    "net/http"
)

Now, lets define a function that will handle HTTP requests for static files:


func serveStaticFile(w http.ResponseWriter, r *http.Request) {
    // Otteniamo il percorso del file richiesto dall'utente
    filePath := r.URL.Path

    // Verifichiamo se il file richiesto esiste nella cartella "static"
    // Se il file non esiste, restituiamo un errore 404 (Not Found)
    if _, err := http.Dir("static").Open(filePath); err != nil {
        http.NotFound(w, r)
        return
    }

    // Se il file esiste, lo serviamo al client
    http.ServeFile(w, r, filePath)
}


Next, we need to configure the path to the static files we want to serve. Lets assume the static files are in a folder called "static" in the root of our project. We use http.FileServer to serve these files:


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

    // Avvia il server sulla porta 8080
    port := ":8080"
    println("Server in ascolto sulla porta", port)
    err := http.ListenAndServe(port, nil)
    if err != nil {
        panic(err)
    }
}

We have now configured the server to serve static files from the "static" folder when it receives an HTTP request on the domain root.

Before running the server, lets make sure that in our project folder there is a folder called "static" containing the static files we want to serve (for example, an index.html file, CSS files, images, etc.).