登录
首页 >  Golang >  Go问答

无法在生产环境下生成文件

来源:stackoverflow

时间:2024-02-26 11:24:23 368浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《无法在生产环境下生成文件》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我使用 google cloud platform (gcp) 和 golang。

我的本​​地环境可以运行代码,但生产环境 (gcp) 不能。

我看到日志。 =>

open stylesheet/qrcode.png: no such file or directory 
read-only file system

所以我尝试 chmod。例如)chmod 644 或 777 qrcode.png

我正在尝试创建图像:qrcode.png <= 这是虚拟文件。 但代码无法运行。

还有其他办法吗?

package main

import (
    "fmt"
    "image/png"
    "log" ............

    "github.com/boombuler/barcode"
    "github.com/boombuler/barcode/qr"
)


func createqr() {
    rand.seed(time.now().unixnano())
    result = ""
    for i := 0; i < 4; i++ {
        s := strconv.itoa(rand.intn(10))
        result = result + s
    }
    qrcode, _ := qr.encode(result, qr.m, qr.auto) //info
    qrcode, _ = barcode.scale(qrcode, 200, 200)   //size

    pin, _ = strconv.atoi(result)
    file, _ := os.create("stylesheet/qrcode.png")
    defer file.close()

    // encode the barcode as png
    png.encode(file, qrcode)
    fmt.println(file)

    starttime = time.now()
}
file, _ := os.Create("stylesheet/qrcode.png")

此代码不起作用。


解决方案


如果您要部署到 App Engine Standard,则只能写信给 /tmp folder in the filesystem

请谨慎对待您打算对生成的文件执行的操作。在一个实例的文件系统中生成它并不意味着它可以像应用程序的 CSS 和 JS 文件一样提供服务。此外,实例是无状态的,您的下一个请求可能会命中任何其他实例,并且任何实例通常会被自动缩放程序关闭。

我的建议是:

  • 如果您只想立即提供一次服务,则让您的处理程序仅执行此操作,并将 QR 码 PNG 字节流式传输到 io.Writer(实现 io.Writer),并设置适当的响应标头 content-type。无需使用文件。
  • 如果您需要持久保存生成的图像文件,请将其存储在 Cloud Storage 或 Firestore 中。然后,您需要一个策略来通过 https 正确提供服务(Cloud Storage 中的对象访问权限、Firestore 的 App Engine 处理程序)。

此外,始终检查并处理错误,切勿用 _ 吞掉它们!

到这里,我们也就讲完了《无法在生产环境下生成文件》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>