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 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答