Last active
November 26, 2022 20:26
-
-
Save philcleveland/caa18e00970e9d42d957 to your computer and use it in GitHub Desktop.
GoLang template with image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Index</title> | |
</head> | |
<body> | |
Index page. | |
<!-- This image always fails to load when served from go, but is fine if I just double click the html file --> | |
<img src="someImg.png" alt="Cannot load image" style="width: 200px;height: 400px"> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"html/template" | |
"net/http" | |
) | |
var ( | |
templates *template.Template | |
) | |
func main() { | |
// This is the only way I have found to be able to serve files requested in the templates | |
http.Handle("/static/img/", http.StripPrefix("/static/img/", | |
http.FileServer(http.Dir(path.Join(rootdir, "/static/img/"))))) | |
http.Handle("/static/css/", http.StripPrefix("/static/css/", | |
http.FileServer(http.Dir(path.Join(rootdir, "/static/css/"))))) | |
http.HandleFunc("/", index) | |
templates = template.Must(template.ParseFiles("index.html")) | |
http.ListenAndServe(":8080", nil) | |
} | |
func index(w http.ResponseWriter, r *http.Request) { | |
err := templates.ExecuteTemplate(w, "index.html", nil) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can also directly serve a single static file with
http.ServeFile(w, r, "/static/img/someImg.png")
For numerous static files, then yes, use a
http.FileServer
- I normally have a separate function that I call with different "root"http.FileSystem
types. Having a single method makes life much easier to handle all thehttp.StripPrefix
steps etc.Furthermore, you can also alter the path to your static assets via Template Funcs - eg in the head of my html I may have
I then add to the template.Funcs the template.FuncMap which will return a cached version if it's already been set and will suffix the path with a unix timestamp so that any changes will cache bust eg:
I do the same for my JS files also. Coming from other languages, I found that Go templates seemed to be pretty cumbersome. I wrote a few pieces here if it helps.