-2

I am currently working on a Go web server utilizing the builtin templates.


The current issue I am having is that when I run the web server, it is serving the correct files but it does not load any media on the site.(Such as pictures and fonts) When I run the .html file as it is all media is loaded so I know it has something to do with my back end. Here is my code :

var templates = template.Must(template.ParseGlob("static/*.html"))
...
func index(w http.ResponseWriter, r *http.Request) {
    currentTime := time.Now().Local()
    toSend := payload{
        Date:   currentTime.Format("01-02-2006"),
        Status: "Active",
    }
    t, err := template.ParseFiles("static/index.html")
    if err != nil {
        log.Fatalf("Error parsing template: %v", err)
    }
    t.Execute(w, toSend)
}
...

And here is my file path:

app
 |-main.go
 |-static(contains static files)
     |-media(contains all media)
     |-index.html

This serves the templates perfectly fine with all the required data yet without any media. All help is appreciated thank you!

Ethan
  • 108
  • 2
  • 9
  • Are you serving the static files? I.e. is there another handler registered besides `index` which runs e.g. `http.FileServer`? – Adrian Nov 07 '17 at 21:51
  • No there is not, would I need that if I am using templates? – Ethan Nov 07 '17 at 21:56
  • It has nothing to do with templates; if you're loading the HTML from a server (eg a Go program), then the server also needs to expose any other assets referenced by the HTML (e.g. images etc). When you just load the HTML in the browser directly from disk, the browser loads the assets the same way. – Adrian Nov 07 '17 at 21:58

1 Answers1

0

Answered by @Adrian in the comments, I simply wasn't loading the media assets via the go server for the html to use.

    http.Handle("/media/",http.StripPrefix("/media/",http.FileServer(http.Dir("static/media"))))

Was all I needed

Ethan
  • 108
  • 2
  • 9