我正在使用CHI路由,并提供如下文件:

fileServer := http.FileServer(http.Dir("./static/"))
mux.Handle("/static/*", http.StripPrefix("/static", fileServer))

在html文件中:

<img src="./static/images/img.png" /> 

一切都运行得很好,当判断img.png的路径为http://localhost:8080/static/images/img.png时,这是很好的…但当用户访问个人资料时...

mux.Route("/user", func(mux chi.Router) {
    mux.Use(Auth)
    mux.Get("/profile", handlers.Repo.ProfileGet) // path: /user/profile
})

在用户登录并访问该路径http://localhost:8080/user/profile之后,图像不会出现(因为路径已经改变)...当我判断图像路径时,我发现:http://localhost:8080/user/static/images/img.png而不是http://localhost:8080/static/images/img.png

如何解决此问题?

推荐答案

该问题与在HTML中解析相对URL的方式有关

<img src="./static/images/img.png" />

此路径相对于浏览器中的当前URL进行解析.

要解决此问题,请在您的HTML中使用静态资源的绝对路径.

<img src="/static/images/img.png" />

通过添加前导/,您可以指定应从域的根解析路径

Go相关问答推荐

T的Golang通用切片,其中 *T实现接口

Golang Cososdb-gremlin连接

ChromeDriver不存在(高朗selenium)

Golang使用Run()执行的命令没有返回

重新赋值变量时未清除动态类型-这是错误吗?

Go安装成功但没有输出简单的Hello World

3 字节切片和有符号整数类型之间的转换

Go 中如何调用测试函数?

设置 graphql 的最大文件上传大小(golang)

Go:如何在将 float64 转换为 float32 时判断精度损失

没有任务角色的 AWS CDK ECS 任务定义

我如何使用 TOML fixtures 在使用 Go Buffalo 框架的开发环境中为我的数据库 seeder ?

Golang 通过接口反映/迭代{}

如何将一片十六进制字节转换为整数

httprouterhttp.HandlerFunc() 是如何工作的?

如何扩充 ResponseWriter 的 Header() 返回的 map

gopls 为 github.com/Shopify/sarama 返回错误gopls: no packages returned: packages.Load error

Golang 泛型同时具有接口和实现

Go 1.18 泛型如何使用接口定义新的类型参数

在 Go 泛型中,如何对联合约束中的类型使用通用方法?