Sling Academy
Home/Golang/Building File Servers in Go

Building File Servers in Go

Last updated: November 27, 2024

Building file servers in Go is an essential skill for developers looking to deliver web content effectively. Go offers a concise, efficient way to create HTTP servers that can serve static files like HTML, CSS, JavaScript, images, and more. In this article, we'll explore how to set up a basic file server using Go.

Setting up your Go environment

To build a file server, ensure you have Go installed on your machine. If not, you can download it from golang.org.

Creating a basic file server

Let's dive straight into coding. We'll start by creating a simple Go file server capable of serving files from a directory.


package main

import (
    "net/http"
    "log"
)

func main() {
    // Define the directory you want your file server to serve.
    dir := "."

    // Serve the contents of the "dir" directory.
    fs := http.FileServer(http.Dir(dir))

    // Use the net/http package to listen and serve on port 8080.
    http.Handle("/", fs)

    // Start and log the status of the server.
    log.Println("Listening on :8080")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal(err)
    }
}

To run the server, save this code to a file named main.go and execute it by running go run main.go in the terminal. Then, open http://localhost:8080 in your web browser to access the served files.

Serving files from a specific directory

If you want the server to serve files from a specific directory other than your current directory, set the dir variable to the desired path:


dir := "./public"

Remember to create the public directory and place some files in it to test the server.

Handling 404 errors

You can customize your file server to display a custom 404 page whenever a requested file is not found. First, create a 404.html page in your directory. Then modify the handler like this:


package main

import (
    "net/http"
    "log"
    "os"
)

func custom404Handler(w http.ResponseWriter, r *http.Request) {
    fs := http.FileServer(http.Dir("."))
    _, err := os.Stat(r.URL.Path[1:])
    if os.IsNotExist(err) {
        // Serve a custom 404 error page
        http.ServeFile(w, r, "404.html")
    } else {
        // Serve the file if it exists
        fs.ServeHTTP(w, r)
    }
}

func main() {
    http.HandleFunc("/", custom404Handler)

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

Now, if a file is not found, it serves the 404.html file instead.

Conclusion

In this article, we've walked through creating a basic file server in Go. We started with setting up a minimal server and then enhanced it by serving a specific directory and added a custom 404 page. This is just the beginning of what you can achieve with Go when building a file server. Explore additional features such as SSL, integrating with frameworks, or handling more complex request routing to expand your basic file server.

Next Article: Serving Static Files with Go HTTP

Previous Article: Using TLS and Certificates for Secure Networking in Go

Series: Networking and Server

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant