Sling Academy
Home/Golang/Serving Static Files with Go HTTP

Serving Static Files with Go HTTP

Last updated: November 27, 2024

Introduction

When building web applications with Go, you may need to serve static files such as images, CSS files, or JavaScript files from your web server. Go provides a simple and efficient way to handle static files using the net/http package.

Setting Up a Static File Server in Go

In this section, we will walk through the steps to set up a simple static file server in Go. We'll use the http.FileServer and http.StripPrefix functions to serve files from a directory.

package main

import (
    "net/http"
    "log"
)

func main() {
    // Serve files from the "static" directory
    fileServer := http.FileServer(http.Dir("./static"))
    
    // Strip the "/static/" prefix when looking for files
    http.Handle("/static/", http.StripPrefix("/static", fileServer))

    // Start the server on port 8080
    log.Println("Starting server on :8080")
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}

Code Walkthrough

  • fileServer := http.FileServer(http.Dir("./static")): This line initializes a file server handler that will serve files from the ./static directory.
  • http.Handle("/static/", http.StripPrefix("/static", fileServer)): This sets up the HTTP route so that any request to /static/... will serve files relative to the ./static directory.
  • http.ListenAndServe(":8080", nil): This function starts the HTTP server on port 8080, with the file server serving requests.

Testing the Static File Server

First, create a directory named static and add some files you want to serve. For example, you could add an index.html file. The directory structure may look like this:


/static
    ├── index.html
    └── styles.css

Now run your Go application and open your browser. Enter http://localhost:8080/static/index.html, and you should see the contents of your index.html file. Similarly, enter http://localhost:8080/static/styles.css to access the CSS file.

Customizing with Middleware

You may want to add logging or serve files only when a specific condition is met. This can be done by wrapping your file server handler with a custom middleware function.

package main

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

func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Println("Request received:", r.URL.Path)
        next.ServeHTTP(w, r)
    })
}

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

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

In this updated code, every request to the server will be logged to the console with the route accessed.

Conclusion

Serving static files in Go is straightforward with the http package. By understanding the basics of handlers and middleware, you can easily extend this functionality to fit more complex requirements. Use this guide as a foundation and integrate these principles into your own projects.

Next Article: Understanding Context for Request Management in Go

Previous Article: Building File Servers 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