Skip to content

Instantly share code, notes, and snippets.

@mhewedy
Created October 4, 2019 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhewedy/65895bced03e75167f2c78cc08994cb8 to your computer and use it in GitHub Desktop.
Save mhewedy/65895bced03e75167f2c78cc08994cb8 to your computer and use it in GitHub Desktop.
workaround #golang packr2 issue with index.html
package main
import (
"github.com/gobuffalo/packr/v2"
"net/http"
"path/filepath"
"strings"
)
var extensionToContentType = map[string]string{
".html": "text/html",
".js": "application/javascript",
".css": "text/css",
}
func BuildHttpHandlers(box *packr.Box) {
list := box.List()
for index := range list {
path := list[index]
url := path
if strings.HasSuffix(url, "index.html") {
url = strings.TrimSuffix(url, "index.html")
}
url = "/" + url
http.HandleFunc(url, func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Add("Content-type", extensionToContentType[filepath.Ext(path)])
bytes, err := box.Find(path)
if err != nil {
logIfError(err)
}
_, _ = writer.Write(bytes)
})
}
}
// then call it like this:
/*
BuildHttpHandlers(packr.New("myBox", "./templates"))
*/
@mhewedy
Copy link
Author

mhewedy commented Oct 7, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment