shadow/utils/template_funcs.go

75 lines
1.3 KiB
Go

package utils
import (
"fmt"
"github.com/goccy/go-json"
"html/template"
"log"
"mime"
"os"
"strings"
)
func ViteAsset(src string, attrs ...string) template.HTML {
file, err := os.ReadFile("dist/.vite/manifest.json")
if err != nil {
log.Fatalln(err)
}
var viteManifestData map[string]map[string]interface{}
if err := json.Unmarshal(file, &viteManifestData); err != nil {
log.Fatalln(err)
}
src = strings.TrimPrefix(src, "/")
var element string
info, ok := viteManifestData[src]
if !ok {
return ""
}
filenameSplit := strings.Split(info["file"].(string), ".")
if len(filenameSplit) < 2 {
return ""
}
fileExt := filenameSplit[len(filenameSplit)-1]
mimeType := mime.TypeByExtension("." + fileExt)
if strings.HasPrefix(mimeType, "image/") {
element = fmt.Sprintf(`<img src="%s"`, info["file"].(string))
for _, attr := range attrs {
element += fmt.Sprintf(` %s`, attr)
}
element += "></img>"
} else if strings.Contains(mimeType, "text/javascript") {
element = fmt.Sprintf(`<script type="module" src="%s"`, info["file"].(string))
for _, attr := range attrs {
element += fmt.Sprintf(` %s`, attr)
}
element += "></script>"
} else if strings.Contains(mimeType, "text/css") {
element = fmt.Sprintf(`<link rel="stylesheet" href="%s">`, info["file"].(string))
}
return template.HTML(element)
}