在Google Cloud上托管API时遇到了文件路径的问题。

huangapple go评论80阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年5月30日 13:40:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/67758047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定