I am trying to build a simple webserver. I want to replace all with
<br>
. I wanted to use bytes
for this, because my page body is stored as an []byte
.
I use bytes.ReplaceAll()
for this. But it keeps saying that it's a reference to undefined identifier.
Can someone tell me why? I tried the exact same line within an online Compiler and it worked just fine. Do I miss the library?
See my code below:
import (
"bytes"
"html/template"
"io/ioutil"
"log"
"net/http"
"regexp"
)
type Page struct {
Title string
Body []byte
}
func editHandler(w http.ResponseWriter, r *http.Request, title string) {
p, err := loadPage(title)
if err != nil {
p = &Page{Title: title}
}
// THE LINE THAT CAUSES TROUBLE
p.Body = bytes.ReplaceAll(p.Body, []byte("
"), []byte("<br>"))
renderTemplate(w, "edit", p)
}
The bytes
package is part of the standard library, so it is unlikely that you don't have it if you have the go
tool available to you.
But do note that bytes.ReplaceAll()
was added in Go 1.12, so if you have an older Go SDK, this function will not be available to you.
Execute go version
to find out. Get the latest Go from the official site: https://golang.org/dl/
Further to icza's answer,
For the benefit of Go versions prior to 1.12
, the following are equivalent:
bytes.ReplaceAll(a, b, c)
and
bytes.Replace(a, b, c, -1)
See the implementation of ReplaceAll