Monday, June 16, 2014

Golang: Serving static content using Gorilla

Using the identical directive from ServeMux  "http.Handle("/static/", http.FileServer(http.Dir("./static/")))" for Gorilla to serve static files wasn't working - the directory listing works but clicking on any of the files listed would produce a 404.

There seems to be two ways to configure the mux to serve static content in Gorilla Mux(highlighted in blue)

package main

import (
    "github.com/gorilla/mux"
    "net/http"
)

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)

    //This won't work
    //http.Handle("/static/", http.FileServer(http.Dir("./static/")))

    //These will work
    //first alternative
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))


    //second alternative
    
    r.PathPrefix("/images/").Handler(http.StripPrefix("/images/",
            http.FileServer(http.Dir("images/"))))
    
    http.Handle("/", r)

    http.ListenAndServe(":3000", nil)
}

func HomeHandler(rw http.ResponseWriter, req *http.Request) {

    rw.Write([]byte("You are at /"))
}







1 comment:

Lane said...

Awesome! Thanks.