英文:
Hosted api on google cloud issue with file paths
问题
我在根目录下有一个名为main.go的文件,其中包含一个图像文件。在将golang API托管在Google Cloud上时,我该如何获取文件的路径以提供文件服务(似乎在托管在Google Cloud上时所有文件都会出错)。以下是我目前正在使用的代码:
func ServeImage(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
ex, err := os.Executable()
if err != nil {
panic(err)
}
executableDir := filepath.Dir(ex)
//TODO error
file, err := os.Open(path.Join(executableDir, "/"+params["name"]))
if (err != nil) {
http.Error(w, err.Error(), http.StatusBadRequest)
fmt.Println(err)
}
defer file.Close()
http.ServeContent(w, r, "image", time.Now(), file)
}
我从中得到的错误是:
open /layers/google.go.build/bin/_DSC7451.jpeg: no such file or directory
seeker can't seek
英文:
I have an image file in the root directory with the main.go file. How would I get the path to serve the file while the golang api is hosted on google cloud (seems like all the files get messed up when its hosted on google cloud). Heres the code im using now:
func ServeImage(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
ex, err := os.Executable()
if err != nil {
panic(err)
}
executableDir := filepath.Dir(ex)
//TODO error
file, err := os.Open(path.Join(executableDir, "/"+params["name"]))
if (err != nil) {
http.Error(w, err.Error(), http.StatusBadRequest)
fmt.Println(err)
}
defer file.Close()
http.ServeContent(w, r, "image", time.Now(), file)
}
The error i get from this is:
open /layers/google.go.build/bin/_DSC7451.jpeg: no such file or directory
seeker can't seek
答案1
得分: 0
如果您正在使用应用引擎,那么您实际上无法访问文件系统。您应该使用云存储来读写文件。这将使您的文件可以在服务的所有实例之间访问,无论何时可能运行。
英文:
If you are using app engine then you don't really have access to file system. https://cloud.google.com/appengine/docs/standard/runtimes
You should be using cloud storage to write and read files. That will allow your files to be accessible across all the instances of your service that may be running at any given time.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论