-
Notifications
You must be signed in to change notification settings - Fork 197
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Embed static assets #54
Comments
Yes, you can embed all of those types of files by using the annotation: // Assets represents the embedded files.
//go:embed *.tmpl pages/*.tmpl static/*.css static/*.png
var Assets embed.FS Also, I put together a blog article around it: https://www.josephspurrier.com/how-to-embed-assets-in-go-1-16 |
When we refer to existing
it calls static assets served by static controller Should I make any change in the template in order to use the embedded css? |
Yes, you'll need to make changes to this function to support it: https://github.com/josephspurrier/gowebapp/blob/embedded-templates/app/controller/static.go. I haven't tested this code, but this is probably how I would approach it: package ambient
import (
"bytes"
"embed"
"io/fs"
"io/ioutil"
"net/http"
"path"
"strings"
"time"
)
// Assets represents the embedded files.
//go:embed static/css/*.css static/js/*.js
var Assets embed.FS
// Static maps static files
func Static(w http.ResponseWriter, r *http.Request) {
// Disable listing directories
if strings.HasSuffix(r.URL.Path, "/") {
Error404(w, r)
return
}
filepath := r.URL.Path
// Determine if an embedded asset is available before service static file.
fsys, err := fs.Sub(Assets, ".")
if err == nil {
// Open the file.
f, err := fsys.Open(filepath)
if err == nil {
defer f.Close()
// Get the contents.
ff, err := ioutil.ReadAll(f)
if err != nil {
Error404(w, r)
return
}
// Assets all have the same time so it's pointless to use the FS
// ModTime.
now := time.Now()
http.ServeContent(w, r, path.Base(filepath), now, bytes.NewReader(ff))
return
}
}
http.ServeFile(w, r, r.URL.Path[1:])
} You'll also need to make changes to this file: https://github.com/josephspurrier/gowebapp/blob/embedded-templates/app/shared/view/plugin/taghelper.go. I'd probably create new funcmap like |
in branch embedded-templates I'm just wondering, can I also embed static assets (js, css, png etc.) in
static
directory ? So I can distribute my binary without static folderI've read https://github.com/elazarl/go-bindata-assetfs but still unable to make it works.
The text was updated successfully, but these errors were encountered: