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.
. . .

Application Structure

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
body {color: #c0392b}

Once those files are created, the code we need to get up and running is wonderfully compact:

Routing

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.

File: app.go
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().
  1. 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.
  2. 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...

And open localhost:3000/example.html in your browser. You should see the HTML page we made with a big red heading.
. . .

Gopher

Feb 19 2020

Write your response...

On a mission to build Next-Gen Community Platform for Developers