diff --git a/assets/fingerprint.go b/assets/fingerprint.go index 255d407..aa75282 100644 --- a/assets/fingerprint.go +++ b/assets/fingerprint.go @@ -9,6 +9,18 @@ import ( "strings" ) +// Path returns the fingerprinted path for a given +// file. If an error occurs during the process, it +// returns the original name. +func (m *manager) Path(name string) string { + path, err := m.PathFor(name) + if err != nil { + return name + } + + return path +} + // PathFor returns the fingerprinted path for a given // file. If the path passed contains the hash it will // return the same path only in GO_ENV=development @@ -23,6 +35,8 @@ func (m *manager) PathFor(name string) (string, error) { hashed, ok := m.fileToHash[normalized] m.fmut.Unlock() + // Return cached hashed filename if available + // and not in development environment if ok && os.Getenv("GO_ENV") != "development" { return path.Join("/", m.servingPath, hashed), nil } diff --git a/assets/fingerprint_test.go b/assets/fingerprint_test.go index afedc43..60313cc 100644 --- a/assets/fingerprint_test.go +++ b/assets/fingerprint_test.go @@ -59,7 +59,7 @@ func TestFingerprint(t *testing.T) { } ch := make(chan struct{}, goroutines) - for i := 0; i < goroutines; i++ { + for i := range goroutines { go func(id int) { defer func() { ch <- struct{}{} @@ -312,6 +312,35 @@ func TestFingerprint(t *testing.T) { } }) }) + + t.Run("Path", func(t *testing.T) { + t.Run("returns fingerprinted path on success", func(t *testing.T) { + fingerprintedPath, err := m.PathFor("main.js") + if err != nil { + t.Fatalf("PathFor failed: %v", err) + } + + path := m.Path("main.js") + if path != fingerprintedPath { + t.Errorf("expected %q, got %q", fingerprintedPath, path) + } + }) + + t.Run("returns original name on error", func(t *testing.T) { + originalName := "nonexistent.js" + path := m.Path(originalName) + + if path != originalName { + t.Errorf("expected %q, got %q", originalName, path) + } + + // Also check the error from PathFor to be sure + _, err := m.PathFor(originalName) + if err == nil { + t.Errorf("expected PathFor to return an error for %q", originalName) + } + }) + }) } func TestReadFile(t *testing.T) {