I'm trying to serve a static html file, and this file has script tags that point to other resources. I want to serve the html file from one directory but then redirect requests for assets to another directory. This is how I'm setting it up now:
// server.go
import (
"fmt"
"html/template"
"log"
"net/http"
"path"
"time"
)
func handle(w http.ResponseWriter, r *http.Request) {
lp := path.Join("./", "index.html")
fmt.Println(lp)
tmpl, err := template.ParseFiles(lp)
if err != nil {
log.Fatal(err)
}
tmpl.ExecuteTemplate(w, "index", nil)
}
func main() {
fs := http.FileServer(http.Dir("../../app_assets/"))
http.Handle("/assets", fs)
http.HandleFunc("/static/", handle)
fmt.Println("Go Server listening on port 8000")
http.ListenAndServe(":8000", nil)
}
Here is my template:
<!-- index.html -->
{{define "index"}}
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="assets/css/libs.css" type="text/css" />
</head>
<body>
<script type="text/javascript" src="assets/js/libs.js"></script>
<h1> Hello </h1>
</body>
</html>
{{end}}
I'm able to serve the index file from localhost:8000/static/
, but asset requests are not going to the assets folder two levels up (../../
). What am I doing wrong?
NOTE:
I'm getting this error in the console when libs.js is loaded:
Uncaught SyntaxError: Unexpected token <
This leads me to believe that the request for the libs.js
file is being redirected to the html markup.
How is this happening?
NOTE 2:
When I browse the result of the request for libs.js
, I see the html markup. Even after using StripPrefix
as advised below. What am I doing wrong?