Created
October 4, 2019 21:42
-
-
Save mhewedy/65895bced03e75167f2c78cc08994cb8 to your computer and use it in GitHub Desktop.
workaround #golang packr2 issue with index.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
see https://github.com/mhewedy/gitblame/blob/master/Packr.go