我在文件夹里有一个文件
files
位于我的golang项目目录的根目录中,名为
test.jpg
. 那就是
./files/test.jpg
我想为自己的前端服务,但我遇到了困难。
我的Golang项目在Docker文件中,随附以下卷。(基本上是这样说的
/go/.../webserver
在Docker容器中可以读写
./
在服务器上)
volumes:
- ./:/go/src/github.com/patientplatypus/webserver/
我正在使用
gorilla/mux
路由定义如下:
r := mux.NewRouter()
以下是我试图使路径前缀正确格式化的一些尝试:
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
到我的前端
空响应.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认证,但在本例中它忽略了这个路由,并且有中间件可以处理CORS。
相关行突出显示:
https://gist.github.com/patientplatypus/36230e665051465cd51291e17825f1f5#file-main-go-L122
.
另外,这里是我的docker compose文件,它显示了卷是什么(请忽略sleep命令以引导postgres-我理解这不是理想的实现)
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为空)。仅供参考,我已经确认了一个有效的公理,但这并不能解决问题。