在Go模板中显示变量图像

在Go模板中显示变量图像,go,go-templates,Go,Go Templates,我在Go web应用程序中使用了一个模板,该模板应该根据访问者来自哪个国家显示图像 对于图像,我使用文件服务器 http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("images")))) 在模板中传递变量country,以便应用程序知道显示哪个标志 <img id='flag' src='images/{{ .Country}}.png'> 谁能帮我解决这个问题 我传递的字符

我在Go web应用程序中使用了一个模板,该模板应该根据访问者来自哪个国家显示图像

对于图像,我使用文件服务器

http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("images"))))
在模板中传递变量country,以便应用程序知道显示哪个标志

<img id='flag' src='images/{{ .Country}}.png'>
谁能帮我解决这个问题

我传递的字符串添加了%0a,这将导致img的src 错

输出:

"US\n"
"US"

很可能
.Country
的值已经包含尾随的
\x0a
字符(这是一个换行符
\n
)。像
fmt.Printf(“%q”,国家)一样打印它以进行验证。如果是这样,您必须使用例如
strings.TrimSpace()
.Thx将其剥离,这就解决了问题!
<img id='flag' src='images/BE.png'>
resp3, err := http.Get("https://ipinfo.io/country")
if err != nil {
    fmt.Println(err)
}
bytes3, _ := ioutil.ReadAll(resp3.Body)
country := string(bytes3)
<img id='flag' src='images/BE%0A.png'>
<img id='flag' src='images/BE.png'>
package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    resp3, err := http.Get("https://ipinfo.io/country")
    if err != nil {
        fmt.Println(err)
    }
    bytes3, err := ioutil.ReadAll(resp3.Body)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("%q\n", bytes3)
    country := string(bytes.TrimRight(bytes3, "\n"))
    fmt.Printf("%q\n", country)
}
"US\n"
"US"