I'm writing a simple web server to serve static files. Any HTML file being served needs to be modified "on the go" to include some HTML just before its closing </body> tag.
I achieved it with the below code and it works, however is there perhaps a more efficient way of doing it? I'm beginner in Go and this code needs to be super performant.
// error handling etc omitted for brevity
dir := http.Dir("my/path")
content, _ := dir.Open("my_file")
var bodyBuf strings.Builder
var contentBuf *bytes.Buffer
io.Copy(&bodyBuf, content)
defer content.Close()
if strings.HasSuffix("some/web/uri", ".html") {
new_html_content := "<whatever></body>"
bodyRpld := strings.Replace(bodyBuf.String(), "</body>", new_html_content, 1)
contentBuf = bytes.NewBuffer([]byte(bodyRpld))
} else {
contentBuf = bytes.NewBuffer([]byte(bodyBuf.String()))
}
d, _ := content.Stat()
http.ServeContent(w, r, "my/path", d.ModTime(), bytes.NewReader(contentBuf.Bytes()))
Thanks!