我试图建立一个小型网站,我使用html / template创建动态页面。页面上的一件事是这些URL中的URL列表,有时我需要字符编码。用于诸如ô(%C3%B4)之类的特殊字符。
当我尝试使用html / template将变量解析为页面时,得到以下结果:%!c(MISSING)3%!b(MISSING)4。我不知道这是怎么了
type Search_list struct {
Search_name string
Search_url string
Search_price float64
}
func generateSearchPage(language int, q string) (string, error) {
/* ommited, fetshing data from elasticsrearch*/
sl := []Search_list{}
var urle *url.URL
//looping through ES results and putting them in a custom List
for _, res := range data.Hits.Hits {
//
//Encode Url
var err error
urle, err = url.Parse(res.Source.URL)
if err != nil {
continue
// TODO: add log
}
//I've tried already the following:
fmt.Println(res.Source.URL) //ô
fmt.Println(url.QueryUnescape(res.Source.URL)) //ô
fmt.Println(urle.String()) //%C3%B4
u, _ := url.QueryUnescape(res.Source.URL)
sl = append(sl, Search_list{res.Source.Name, u, res.Source.Price})
}
var buffer bytes.Buffer
t := template.New("Index template")
t, err = t.Parse(page_layout[language][PageTypeSearch])
if err != nil {
panic(err)
}
err = t.Execute(&buffer, Search_data{
Title: translations[language]["homepage"],
Page_title: WebSiteName,
Listed_items: sl,
})
if err != nil {
panic(err)
}
return buffer.String(), nil // %!c(MISSING)3%!b(MISSING)4
}
最佳答案
@ Moshe Revah
感谢您的帮助,与此同时,我发现了错误
稍后在代码中,我将生成的页面发送给http客户端
fmt.Fprintf(w, page) // Here was the error b/c of the % symbols
我只是将其更改为
fmt.Fprint(w, page)
而且效果很好