Golang Code

Serve Static Assets using the Mux Router

· 145 words · 1 minute read #assets #css #dir #file #handler #images #img #js #mux #router #serve #server #static

Using a router is great when passing off incoming requests to functions to handle and return data. Often though, you just want to serve an entire directory and make everything inside it public. This is useful for images, styles and javascript.

In this example we’re using the Gorilla mux router (“HTTP request multiplexer”) and we have setup a new route for the entire directory. We’re using static as the folder name to serve, which we pass to our FileServer() as a new route on the router.

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

const (
    STATIC_DIR = "/static/"
    PORT       = "8080"
)

func main() {
    router := NewRouter()
    err := http.ListenAndServe(":"+PORT, router)
    if err != nil {
        log.Fatal("ListenAndServe Error: ", err)
    }
}

func NewRouter() *mux.Router {
    router := mux.NewRouter().StrictSlash(true)

    // Server CSS, JS & Images Statically.
    router.
        PathPrefix(STATIC_DIR).
        Handler(http.StripPrefix(STATIC_DIR, http.FileServer(http.Dir("."+STATIC_DIR))))

    return router
}
Image of Author Edd Turtle

Author: Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below. Thanks for reading!