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 Pyqt 如何正确的关掉Qthread,并且释放其中的锁?
  • ¥30 网站服务器通过node.js部署了一个项目!前端访问失败
  • ¥15 WPS访问权限不足怎么解决
  • ¥15 java幂等控制问题
  • ¥15 海湾GST-DJ-N500
  • ¥15 氧化掩蔽层与注入条件关系
  • ¥15 Django DRF 如何反序列化得到Python对象类型数据
  • ¥15 多数据源与Hystrix的冲突
  • ¥15 如何在线硕士了解,广告太多,希望有真实接触过的人回答下?(标签-学习|关键词-在线硕士)
  • ¥15 zabbix6.4与frp如何进行联动