Post

Go http.FileServer()

How to use http.FileServer in Go to serve static files from the filesystem and reference them in handler responses.

This program sets up a Go HTTP server that serves static files from the current directory using http.FileServer(http.Dir(".")). It also registers a custom /tesla route that returns an HTML image tag pointing to a file served by the file server. This is a common pattern for serving images, CSS, and JavaScript alongside dynamic routes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import (
	"io"
	"net/http"
)

func main() {
	http.Handle("/", http.FileServer(http.Dir(".")))
	http.HandleFunc("/tesla", teslaFromFileSystem)
	http.ListenAndServe(":8080", nil)

}

func teslaFromFileSystem(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	io.WriteString(w, `<img src="tesla.jpg">`)
}

This post is licensed under CC BY 4.0 by the author.