dsam70528 2019-01-21 15:43
浏览 42
已采纳

如何在GCP云功能内加载本地资产?

I'm building a tiny GCP cloud function in Golang that returns a generated PNG file when calling it via HTTP. I deployed my code via ZIP-Upload in the Google Cloud Console. Currently it gets called properly and the code gets compiled etc. But in my code I have to load several local files - a font and a .png image. I bundled those in the ZIP I uploaded and the files are visible in the Source-View in GCP. All files (images, fonts and go-files) are within the same directory.

When calling the cloud function the log states the following:

2019/01/21 14:59:31 open /english.png: no such file or directory

I tried to change the way i build the path to the file in go. I already used /german.png statically, used several attempts to build the path dynamically.

I'm not 100 percent sure if this is the way to go, but it is my first experiment with "serverless" and i am willing to get it done the "right" way.

import "github.com/fogleman/gg"


func main() {
    ex, err := os.Executable()
    if err != nil {
        panic(err)
    }
    executableDir := filepath.Dir(ex)

    img, err :=gg.LoadPNG(path.Join(executableDir, "./english.png"))
    if err != nil {
        log.Fatal(err)
    }
}

Currently the file can not be found in any attempt i made. Maybe the path the images get "deployed" into are different from the ones i tried - i have not found any note on that in the documentation. I'd obviously expect it to be loaded properly.

  • 写回答

1条回答 默认 最新

  • doudong1117 2019-01-21 16:40
    关注

    I created http functions with the following structure:

    api
    |--test.txt
    |--api.go
    

    And wrote simple function to reply with file content:

    package api
    
    import (
        "io/ioutil"
        "net/http"
    )
    
    // FileTest func
    func FileTest(w http.ResponseWriter, r *http.Request) {
        content, err := ioutil.ReadFile("./test.txt")
        if err != nil {
            w.WriteHeader(http.StatusInternalServerError)
            w.Write([]byte(err.Error()))
            return
        }
    
        w.Write(content)
    }
    

    It returns the file content without any problems. https://us-central1-clickshield24m.cloudfunctions.net/api

    So in your case I would try change the path to gg.LoadPNG("./english.png")

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载