Serving Images along with Template Parsing

I am having a problem getting images to display on served html template pages from a static directory on my machine.

Here is my code:


import (
	"fmt"
	"html/template"
	"net/http"

	data "github.com/CurtGreen/SocialDirectory/Data"
	"github.com/CurtGreen/SocialDirectory/WebUtils"
	"github.com/gorilla/mux"
)

func main() {
	data.Init()
	multiplex := mux.NewRouter()
	multiplex.StrictSlash(true)
	multiplex.Handle("/Public/", http.FileServer(http.Dir("Public")))
	multiplex.HandleFunc("/", WelcomeHandler)
	multiplex.HandleFunc("/directory/", DirectoryHandler)
	multiplex.HandleFunc("/dashboard/{userId}/", DashboardHandler)

	http.ListenAndServe("127.0.0.1:8000", multiplex)
}

// WelcomeHandler Handles requests for welcome Page
func WelcomeHandler(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("Templates/mainlayout.html", "Templates/publicnav.html")
	t.Execute(w, "Welcome!")

	fmt.Println(WebUtils.ServeLog(r))
}

// DirectoryHandler Handles requests for directory
func DirectoryHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "<h1>Directory Page!</h1>")
	fmt.Println(WebUtils.ServeLog(r))
}

// DashboardHandler Handles requests for dashboard
func DashboardHandler(w http.ResponseWriter, r *http.Request) {

	fmt.Fprintf(w, fmt.Sprintf("<h1>Dashboard! %v</h1>", "Guy Fiori"))
	fmt.Println(WebUtils.ServeLog(r))
}

Is there something I’m missing, or is that not what http.FileServer is for?

iirc gorilla/mux does explicit path handling, so multiplex.Handle("/Public/", http.FileServer(http.Dir("Public"))) will only match to 127.0.0.1:8000/Public/ not 127.0.0.1:8000/Public/something.jpg

Try PathPrefix - http://www.gorillatoolkit.org/pkg/mux#Route.PathPrefix

You want something like:

multiplex.PathPrefix("/Public/").Handler(http.FileServer(http.Dir("Public")))

And you likely need to also use the StripPrefix handler - https://golang.org/pkg/net/http/#StripPrefix giving you something like below (I haven’t tested it though)

multiplex.PathPrefix("/Public/").Handler(http.StripPrefix("/Public/", http.FileServer(http.Dir("Public")))))
1 Like

Thank you for that, now it is working :slight_smile:
I thought it might have something to do with gorilla/mux’s path handling

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.