Hey folks!
Want some feedback on my small side project. I’ve worked a lot with Django in the past. When I started to learn Go I felt the lack of many familiar tools. One of these tools was static files management. Django has built-in command collectstatic
to collect asset files from a different locations, tag file names with a hash and copy them to a separate directory. collectstatic
also fix references to other assets in .css
files. I tried to find similar tool in Go and community packages but to no avail. So I decide to write my own implementation.
It has a very simple usage.
- Install
go get -u github.com/catcombo/go-staticfiles/...
- Run
collectstatic --output web/staticfiles --input assets/static --input media/
to copy and tag files from a different locations to the output dir. - Serve files via
http.FileServer
:
staticFilesPrefix := "/static/"
storage, err := staticfiles.NewStorage("web/staticfiles")
http.Handle(staticFilesPrefix, http.StripPrefix(staticFilesPrefix, http.FileServer(storage)))
You also be able to get reverse link to a processed file in templates:
staticFilesPrefix := "/static/"
staticFilesRoot := "output/dir"
storage, err := NewStorage(staticFilesRoot)
funcs := template.FuncMap{
"static": func(relPath string) string {
return staticFilesPrefix + storage.Resolve(relPath)
},
}
tmpl, err := template.New("").Funcs(funcs).ParseFiles("templates/page.html")
Now you can call static
function in templates like this {{static "css/style.css"}}
which will be converted /static/css/style.d41d8cd98f00b204e9800998ecf8427e.css
(hash may vary).
Hope someone find it useful and want some feedback on how to make it better.