Skip to content

42z-io/hashembed

Repository files navigation

Hash Embed

Build and Test Coverage Status GitHub Tag License Docs

Logo

hashembed is an embed.FS with support for reading files with virtual content hashes embedded in the file name.

hashembed is useful if you are embedding static assets directly into your application and want to facilitate serving these files with very long duration client-side caching.

Usage

package main

import (
  "embed"
  "github.com/42z-io/hashembed"
)

//go:embed testdata/*
var embedded embed.FS

func main() {
  embedded, _ := hashembed.Generate(embedded)
  path := embedded.GetHashedPath("testdata/test.css")
  fmt.Printf(path)
  // Output: testdata/test.8d77f04c3be2abcd554f262130ba6c30f277318e66588b6a0d95f476c4ae7c48.css
  data, _ := embedded.ReadFile(path)
  fmt.Println(string(data[:])
  // Output: body { width: 100%; }
}

Use Case

Here is a psuedo example using Fiber, and Templ

//go:embed dist/*
var data embed.FS
var hashedData := hashembed.Generate(data)

// Template
templ {
    <script src={ "/static/" + hashedData.GetHashedPath("dist/my_file.css") }>
}
// <script src="/static/dist/my_file.HASH_CODE_HERE.css">

// Filesystem middleware
app.Use("/static", filesystem.New(
  filesystem.Config{
      Root:       http.FS(hashedData),
      Browse:     false,
      MaxAge:     600000,
  }
))