草庐IT

image - 如何使用 go 脚本在 Google-Cloud-Storage 中获取我的图像(base64)

coder 2023-07-02 原文

我一直在 go 中寻找示例 GAE 脚本从 PageSpeed Insights 的结果截图中获取我的图像并使用 Kohana/Cache 将其保存为 json_decode 对象到 Google 云存储 (GCS)

使用此方法的原因很简单,因为我发现此 Kohana 模型是将文件写入 GCS 的最便捷方式,尽管我也在寻找其他方式,例如 this使用 Blobstore 将文件写入 GCS在 Go API 文件已被弃用时为它们提供服务,如记录 here .

这是包含屏幕截图图像数据 (base64) 的存储对象的形式,该数据在默认应用程序存储桶中以公共(public)方式保存,对象名称为 images/thumb/mythumb.jpg :

stdClass Object
(
    [screenshot] => stdClass Object
        (
            [data] => _9j_4AAQSkZJRgABAQAAAQABAAD_...= // base64 data
            [height] => 240
            [mime_type] => image/jpeg
            [width] => 320
        )

    [otherdata] => Array
        (
            [..] => ..
            [..] => ..
        )

)

我想获取设置为 public 的图像使用我自定义的 url 如下,通过 go module 进行,我还需要它在特定时间过期,因为我已经设法定期更新图像内容本身:

http://myappId.appspot.com/image/thumb/mythumb.jpg

我在 disptach.yaml 中设置将所有图像请求发送到我的 go 模块,如下所示:

- url: "*/images/*"
  module: go

并在 go.yaml 中设置处理程序以按如下方式处理图像请求:

handlers:
- url: /images/thumb/.*
  script: _go_app

- url: /images
  static_dir: images

使用这个指令,我得到了所有 /images/ 请求(/images/thumb/ 请求除外)提供来自静态目录的图像,并且 /images/thumb/mythumb.jpg 转到模块应用程序。

所以在名为 thumb.go 的应用程序文件中留下了我必须使用的代码(参见 ????),如下所示:

package thumb

import(
    //what to import
    ????
    ????
)

const (
    googleAccessID            = "<serviceAccountEmail>@developer.gserviceaccount.com"
    serviceAccountPEMFilename = "YOUR_SERVICE_ACCOUNT_KEY.pem"
    bucket                    = "myappId.appspot.com"
)

var (
    expiration = time.Now().Add(time.Second * 60) //expire in 60 seconds
)

func init() {
    http.HandleFunc("/images/thumb/", handleThumb)
}

func handleThumb(w http.ResponseWriter, r *http.Request) {
    ctx := cloud.NewContext(appengine.AppID(c), hc)
    ???? //what code to get the string of 'mythumb.jpg' from url
    ???? //what code to get the image stored data from GCS
    ???? //what code to encoce base64 data
    w.Header().Set("Content-Type", "image/jpeg;")    
    fmt.Fprintf(w, "%v", mythumb.jpg)
}

我从一些例子中提取了很多代码,比如 this , thisthis但到目前为止还没有一件作品。我还尝试了 this 中的示例这几乎接近 my case但也没有找到运气。

所以一般情况下,主要是因为缺少在我用???? 标记的行上放置的正确代码以及要导入的相关库或路径。我还检查了 GCS permission如果按照描述丢失了某些东西 herehere .

非常感谢您的帮助和建议。

最佳答案

根据我在您的描述中所读到的内容,似乎唯一相关的部分是实际 Go 代码中的 ???? 行。如果情况并非如此,请告诉我。

首先????:“什么代码从url中获取'mythumb.jpg'的字符串”?

通过阅读代码,您希望从类似 http://localhost/images/thumb/mythumb.jpg 的 url 中提取 mythumb.jpgWriting Web Applications 提供了一个工作示例教程:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

这样

http://localhost:8080/monkeys

打印

Hi there, I love monkeys!

第二个????:“从GCS获取图像存储数据的代码是什么”?

您可能希望使用的 API 方法是 storage.objects.get .

您确实链接到了 JSON API Go Examples 之一对于 Google Cloud Storage,这是一个很好的一般引用,但与您要解决的问题无关。该特定示例是为客户端应用程序组合在一起的(因此 redirectURL = "urn:ietf:wg:oauth:2.0:oob" 行)。此外,此示例使用已弃用/过时的 oauth2 和存储包。

对于想要代表自己访问自己的存储桶的应用程序,最干净(且未弃用)的方法之一是使用 golang/oauth2Google APIs Client Library for Go包。

如何通过 golang/oauth2 使用 JSON Web Token auth 进行身份验证的示例包裹是available in the repo :

func ExampleJWTConfig() {
    conf := &jwt.Config{
        Email: "xxx@developer.com",
        // The contents of your RSA private key or your PEM file
        // that contains a private key.
        // If you have a p12 file instead, you
        // can use `openssl` to export the private key into a pem file.
        //
        //    $ openssl pkcs12 -in key.p12 -out key.pem -nodes
        //
        // It only supports PEM containers with no passphrase.
        PrivateKey: []byte("-----BEGIN RSA PRIVATE KEY-----..."),
        Subject:    "user@example.com",
        TokenURL:   "https://provider.com/o/oauth2/token",
    }
    // Initiate an http.Client, the following GET request will be
    // authorized and authenticated on the behalf of user@example.com.
    client := conf.Client(oauth2.NoContext)
    client.Get("...")
}

接下来,不要直接使用 oauth2 客户端,而是使用带有 Google APIs Client Library for Go 的客户端前面提到:

service, err := storage.New(client)
if err != nil {
    fatalf(service, "Failed to create service %v", err)
}

注意与过时的 JSON API Go Examples 的相似之处?

在您的处理程序中,您需要使用 func ObjectsService.Get 获取相关对象。 .假设您知道 objectbucket 的名称,即。

直接从前面的示例中,您可以使用类似于下面的代码来检索下载链接:

if res, err := service.Objects.Get(bucketName, objectName).Do(); err == nil {
    fmt.Printf("The media download link for %v/%v is %v.\n\n", bucketName, res.Name, res.MediaLink)
} else {
    fatalf(service, "Failed to get %s/%s: %s.", bucketName, objectName, err)
}

然后,获取文件,或者用它做任何你想做的事。完整示例:

import (
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/jwt"
    "google.golang.org/api/storage/v1"
    "fmt"
)

...

const (
    bucketName = "YOUR_BUCKET_NAME"
    objectName = "mythumb.jpg"
)

func main() {
    conf := &jwt.Config{
        Email: "xxx@developer.com",
        PrivateKey: []byte("-----BEGIN RSA PRIVATE KEY-----..."),
        Subject:    "user@example.com",
        TokenURL:   "https://provider.com/o/oauth2/token",
     }

    client := conf.Client(oauth2.NoContext)

    service, err := storage.New(client)
    if err != nil {
        fatalf(service, "Failed to create service %v", err)
    }

    if res, err := service.Objects.Get(bucketName, objectName).Do(); err == nil {
        fmt.Printf("The media download link for %v/%v is %v.\n\n", bucketName, res.Name, res.MediaLink)
    } else {
        fatalf(service, "Failed to get %s/%s: %s.", bucketName, objectName, err)
    }

    // Go fetch the file, etc.
}

第三个????:“编码base64数据的代码是什么”?

使用 encoding/base64 非常简单包裹。如此简单,他们包括了一个 example :

package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    data := []byte("any + old & data")
    str := base64.StdEncoding.EncodeToString(data)
    fmt.Println(str)
}

希望对您有所帮助。

关于image - 如何使用 go 脚本在 Google-Cloud-Storage 中获取我的图像(base64),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29148777/

有关image - 如何使用 go 脚本在 Google-Cloud-Storage 中获取我的图像(base64)的更多相关文章

  1. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  2. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  3. C# 到 Ruby sha1 base64 编码 - 2

    我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha

  4. ruby-on-rails - Rails - Carrierwave 进程抛出 ArgumentError : no images in this image list - 2

    在尝试实现应用auto_orient的过程之后!对于我的图片,我收到此错误:ArgumentError(noimagesinthisimagelist):app/uploaders/image_uploader.rb:36:in`fix_exif_rotation'app/controllers/posts_controller.rb:12:in`create'Carrierwave在没有进程的情况下工作正常,但在添加进程后尝试上传图像时抛出错误。流程如下:process:fix_exif_rotationdeffix_exif_rotationmanipulate!do|image|

  5. ruby-on-rails - Rails 基本 Base64 身份验证 - 2

    我正在尝试复制此GETcurl请求:curl-D--XGET-H"Authorization:BasicdGVzdEB0YXByZXNlYXJjaC5jb206NGMzMTg2Mjg4YWUyM2ZkOTY2MWNiNWRmY2NlMTkzMGU="-H"Content-Type:application/json"http://staging.example.com/api/v1/campaigns在Ruby中,通过电子邮件+apikey生成身份验证:auth="Basic"+Base64::encode64("test@example.com:4c3186288ae23fd9661c

  6. ruby - Google-api-ruby-client 翻译 API 示例 - 2

    很高兴看到google代码:google-api-ruby-client项目,因为这对我来说意味着Ruby人员可以使用GoogleAPI-s来完善代码。虽然我现在很困惑,因为给出的唯一示例使用Buzz,并且根据我的实验,Google翻译(v2)api的行为必须与google-api-ruby-client中的Buzz完全不同。.我对“Explorer”演示示例很感兴趣——但据我所知,它并不是一个探索器。它所做的只是调用一个Buzz服务,然后浏览它已经知道的关于Buzz服务的事情。对我来说,Explorer应该让您“发现”所公开的服务和方法/功能,而不一定已经知道它们。我很想听听使用这个

  7. ruby-on-rails - 在 rails 中显示 base64 编码的图像 - 2

    我正在向我的Controller发送一个base64图像并按原样保存它。现在我需要显示该图像。这是我要显示的内容,但未显示图像:"/>为了编码,我使用了这个java脚本函数encodeURIComponent();我的编码图像格式:data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/........ 最佳答案 你不需要解码base64应该可以 关于ruby-on-rails-在rails中显示base64编码的图像,我们在StackOve

  8. ruby-on-rails -/usr/local/lib/libz.1.dylib,文件是为 i386 构建的,它不是被链接的体系结构 (x86_64) - 2

    在我的mac上安装几个东西时遇到这个问题,我认为这个问题来自将我的豹子升级到雪豹。我认为这个问题也与macports有关。/usr/local/lib/libz.1.dylib,filewasbuiltfori386whichisnotthearchitecturebeinglinked(x86_64)有什么想法吗?更新更具体地说,这发生在安装nokogirigem时日志看起来像:xslt_stylesheet.c:127:warning:passingargument1of‘Nokogiri_wrap_xml_document’withdifferentwidthduetoproto

  9. ruby - libxml-ruby 无法在 x86_64 上加载 - 2

    我们在服务器端遇到libxml-rubygem的问题可能是因为它使用x86_64架构:$uname-aLinuxip-10-228-171-642.6.21.7-2.fc8xen-ec2-v1.0#1SMPTueSep110:25:30EDT2009x86_64GNU/Linuxrequire'libxml'LoadError:/usr/local/ruby-enterprise/lib/ruby/gems/1.8/gems/libxml-ruby-1.1.4/lib/libxml_ruby.so:invalidELFheader-/usr/local/ruby-enterprise/

  10. ruby-on-rails - Textmate 'Go to symbol' 相当于 Vim - 2

    在Railcasts上,我注意到一个非常有趣的功能“转到符号”窗口。它像Command-T一样工作,但显示当前文件中可用的类和方法。如何在vim中获取它? 最佳答案 尝试:helptags有各种程序和脚本可以生成标记文件。此外,标记文件格式非常简单,因此很容易将sed(1)或类似的脚本组合在一起,无论您使用何种语言,它们都可以生成标记文件。轻松获取标记文件(除了下载生成器之外)的关键在于格式化样式而不是实际解析语法。 关于ruby-on-rails-Textmate'Gotosymbol

随机推荐