gpt4 book ai didi

go - 在 Go 模板中显示可变图像

转载 作者:数据小太阳 更新时间:2023-10-29 03:40:36 25 4
gpt4 key购买 nike

我在 Go 网络应用程序中使用一个模板,它应该根据访问者来自哪个国家/地区显示图像。

图片我用的是FileServer

http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("images"))))

在模板中传递了变量国家,因此应用程序知道要显示哪个标志。

<img id='flag' src='images/{{ .Country}}.png'>

但是,由于某种原因,我传递的字符串添加了 %0a ,这导致 img 的 src 错误。

<img id='flag' src='images/BE%0A.png'>

预期的输出应该是

<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)

谁能帮我解决这个问题?

最佳答案

the string I pass adds %0a which causes the src of the img to be wrong.

<img id='flag' src='images/BE%0A.png'>

The expected output should be

<img id='flag' src='images/BE.png'>

修剪换行符(0x0A"\n")。例如,

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"

关于go - 在 Go 模板中显示可变图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54112034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com