【发布时间】:2019-02-10 23:27:47
【问题描述】:
我在 Golang 项目目录的根目录中的文件夹 files 中有一个文件,名为 test.jpg。所以那将是./files/test.jpg,我想为我的前端服务,但我遇到了困难。
我的 golang 项目位于一个 docker 文件中,并附有以下卷。 (基本上就是说docker容器中的/go/.../webserver可以读写服务器上的./)
volumes:
- ./:/go/src/github.com/patientplatypus/webserver/
我使用gorilla/mux 进行路由,定义如下:
r := mux.NewRouter()
以下是我尝试正确格式化 PathPrefix 的一些尝试:
r.PathPrefix("/files/").Handler(http.StripPrefix("/files/",
http.FileServer(http.Dir("/go/src/github.com/patientplatypus/webserver/files/"))))
或
r.PathPrefix("/files").Handler(http.FileServer(http.Dir("./files/")))
或
r.PathPrefix("/files/").Handler(http.StripPrefix("/files/",
http.FileServer(http.Dir("./"))))
或
r.PathPrefix("/files/").Handler(http.FileServer(
http.Dir("/go/src/github.com/patientplatypus/webserver/")))
我之前使用以下命令成功写入服务器:
newPath := filepath.Join("/go/src/github.com/patientplatypus/webserver/files",
"test.jpg")
newFile, err := os.Create(newPath)
所以我的直觉是我的第一次尝试应该是正确的,指定了整个/go/.../files/ 路径。
在任何情况下,我的每次尝试都成功地将200OK 返回到我的前端,并带有一个空的 response.data,如下所示:
Object { data: "", status: 200, statusText: "OK",
headers: {…}, config: {…}, request: XMLHttpRequest }
它来自一个简单的 js 前端 http 请求,使用 axios 包:
axios({
method: 'get',
url: 'http://localhost:8000/files/test.jpg',
})
.then(response => {
//handle success
console.log("inside return for test.jpg and value
of response: ")
console.log(response);
console.log("value of response.data: ")
console.log(response.data)
this.image = response.data;
})
.catch(function (error) {
//handle error
console.log(error);
});
我对为什么会发生这种情况的唯一猜测是它看不到文件,因此什么也不返回。
对于这样一个看似微不足道的问题,我处于猜测和检查阶段,不知道如何进一步调试。如果有人有任何想法,请告诉我。
谢谢!
编辑:
为了完全清楚,这里是我的 main.go 文件的全部(只有 150 行)以及所有路由。有一个处理 JWT auth 的中间件,但是在这种情况下它忽略了这条路由,并且有处理 CORS 的中间件。
有问题的行突出显示:https://gist.github.com/patientplatypus/36230e665051465cd51291e17825f1f5#file-main-go-L122。
另外,这是我的 docker-compose 文件,它显示了卷是什么(请忽略启动 postgres 的 sleep 命令 - 我知道这不是理想的实现)
https://gist.github.com/patientplatypus/2569550f667c0bee51287149d1c49568.
应该没有其他必要的调试信息。
另外...有些人希望我证明文件存在于容器中。
patientplatypus:~/Documents/zennify.me:11:49:09$docker exec
backend_app_1 ls /go/src/github.com/patientplatypus/webserver/files
test.jpg
表明确实如此。
澄清:
我没有正确使用 Axios 来缓冲数组并获取图像。该工作的一个示例在这里:
//working example image
var imageurl = 'https://avatars2.githubusercontent.com/u/5302751?v=3&s=88';
//my empty server response
//var imageurl = 'http://localhost:8000/files/test.jpg';
axios.get(imageurl, {
responseType: 'arraybuffer'
})
.then( response => {
console.log('value of response: ', response);
console.log('value of response.data: ', response.data);
const base64 = btoa(
new Uint8Array(response.data).reduce(
(data, byte) => data + String.fromCharCode(byte),
'',
),
);
console.log('value of base64: ', base64);
this.image = "data:;base64," + base64
});
但是,这并没有改变 golang 似乎没有返回任何数据(response.data 为空)的潜在问题。仅供参考,我已确认 axios 可以正常工作,但这并不能解决问题。
【问题讨论】:
标签: file http go gorilla fileserver