Khalil ben ayed
Khalil ben ayed

Reputation: 1

CSS and images from a different folder are not read when rendering template using Golang

I am trying to render a template using the html/template module of Golang. But only CSS files and images from the same folder as the page i am rendering are executed, those located in a different folder are ignored. Here is my code:

func render(w http.ResponseWriter, filename string, data interface{}) {
    tmpl, err := template.ParseFiles(filename)
    if err != nil {
      http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    if err := tmpl.Execute(w, data); err != nil {
      http.Error(w, err.Error(), http.StatusInternalServerError)
    }
  }

For this page for example:

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>Start Connect</title>
  <link href="../css/bootstrap.min.css" rel="stylesheet">
  <link href="one-page.css" rel="stylesheet">
</head>

The one-page.css is executed but not the bootstrap.

Upvotes: 0

Views: 229

Answers (1)

Pascal Riesinger
Pascal Riesinger

Reputation: 53

Using ../css on the web should be avoided and likely is your error source. Your go server likely cannot resolve the file (because you don't have a handler for the ../css URI). So you should change the ../css part to /css and tell your server (you didn't provide details, so I cannot show you code) to handle /css URIs by serving the files.

Assuming that you are using the default net/http mux, your code should look something like:

mux := http.NewServeMux()
mux.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
http.ListenAndServe(":8080", mux)

Upvotes: 2

Related Questions