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")

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

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)