How to Serve Static Sites with Go
learn how to route static assets or static contents. Such as css, js, and image files
In this post we will learn how to route static assets or static contents. Such as css, js, and image files are generally categorized as static assets.
Let's begin with a simple but real-world example: serving vanilla HTML and CSS files from a particular location.
Create a new project, prepare files and folders with the structure according to the following image.
Start by creating a directory to hold the project:
$ mkdir static-site
$ cd static-site
Along with an app.go file to hold our code, and some sample HTML and CSS files in a static directory.
$ touch app.go
$ mkdir -p static/stylesheets
$ touch static/example.html static/stylesheets/main.css
File: static/example.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>A static page</title>
<link rel="stylesheet" href="/stylesheets/main.css">
</head>
<body>
<h1>Hello from a static page</h1>
</body>
</html>
File: static/stylesheets/main.css
Once those files are created, the code we need to get up and running is wonderfully compact:
In contrast to using routing http.HandleFunc(), static asset routing is easier. Please write the following code in app.go, after which we will discuss in detail.
package main
import (
"log"
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("static"))
http.Handle("/", fs)
log.Println("Listening...")
http.ListenAndServe(":3000", nil)
}
Requirements needed for static asset routing are still the same as the routing handler, which needs to be defined by the route and the handler. It's just the difference, the static assets used in routing are http.Handle(), no http.HandleFunc().
The selected route is /static/, then later all requests initiated by /static/will be directed here. Register a route using http.Handle()is different from using routing http.HandleFunc(), more clearly there will be a little explanation in another chapter.
Function http.FileServer()returns object of type http.Handler. This function is useful for serving all http requests, with content defined in the parameters. In this context what is meant is http.Dir("assets"). All contents, whether files or folders, that are in the folder assetswill be processed in the handler.
It's worth pointing out that in Go the pattern "/" matches all request paths, rather than just the empty path.
Go ahead and run the application:
$ go run app.go
Listening...