登录
首页 >  Golang >  Go问答

从 Github Graph QL API 下载图像文件以使用 Golang

来源:stackoverflow

时间:2024-03-07 20:12:26 196浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《从 Github Graph QL API 下载图像文件以使用 Golang》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我们有一个存储图像文件的 github 存储库。

https://github.com/rollthecloudinc/ipe-objects/tree/dev/media

我们希望通过 golang 提供这些图像文件。 golang api 作为 lambda 函数在 aws api 网关上运行。当前状态下进入空白屏幕的功能如下。

func GetMediaFile(req *events.APIGatewayProxyRequest, ac *ActionContext) (events.APIGatewayProxyResponse, error) {
    res := events.APIGatewayProxyResponse{StatusCode: 500}

    pathPieces := strings.Split(req.Path, "/")
    siteName := pathPieces[1]
    file, _ := url.QueryUnescape(pathPieces[3]) // pathPieces[2]

    log.Printf("requested media site: " + siteName)
    log.Printf("requested media file: " + file)

    // buf := aws.NewWriteAtBuffer([]byte{})

    // downloader := s3manager.NewDownloader(ac.Session)

    /*_, err := downloader.Download(buf, &s3.GetObjectInput{
        Bucket: aws.String(ac.BucketName),
        Key:    aws.String("media/" + file),
    })

    if err != nil {
        return res, err
    }*/

    ext := strings.Split(pathPieces[len(pathPieces)-1], ".")
    contentType := mime.TypeByExtension(ext[len(ext)-1])

    if ext[len(ext)-1] == "md" {
        contentType = "text/markdown"
    }

    suffix := ""
    if os.Getenv("GITHUB_BRANCH") == "master" {
        suffix = "-prod"
    }

    var q struct {
        Repository struct {
            Object struct {
                ObjectFragment struct {
                    Text     string
                    IsBinary bool
                    ByteSize int
                } `graphql:"... on Blob"`
            } `graphql:"object(expression: $exp)"`
        } `graphql:"repository(owner: $owner, name: $name)"`
    }
    qVars := map[string]interface{}{
        "exp":   githubv4.String(os.Getenv("GITHUB_BRANCH") + ":media/" + file),
        "owner": githubv4.String("rollthecloudinc"),
        "name":  githubv4.String(siteName + suffix),
    }

    err := ac.GithubV4Client.Query(context.Background(), &q, qVars)
    if err != nil {
        log.Print("Github latest file failure.")
        log.Panic(err)
    }
    // log.Printf(q.Repository.Object.ObjectFragment.Text)
    // json.Unmarshal([]byte(q.Repository.Object.ObjectFragment.Text), &obj)
    // log.Printf("END GithubFileUploadAdaptor::LOAD %s", id)

    log.Print("content")
    log.Print(q.Repository.Object.ObjectFragment.Text)

    res.StatusCode = 200
    res.Headers = map[string]string{
        "Content-Type": contentType,
    }
    res.Body = q.Repository.Object.ObjectFragment.Text //base64.StdEncoding.EncodeToString([]byte(q.Repository.Object.ObjectFragment.Text))
    res.IsBase64Encoded = true
    return res, nil
}

完整的 api 文件可以在下面查看,但不包括上面迁移到 github 时所做的更改。该 api 使用 s3 运行良好。然而,我们现在正尝试迁移到 github 来进行对象存储。已成功实现写入,但使用我们的 lambda 读取文件时遇到上述困难。

https://github.com/rollthecloudinc/verti-go/blob/master/api/media/main.go

请求帮助了解如何使用 aws 上的 golang lambda 从我们的 github 存储库提供图像文件,可以在此处作为空白屏幕进行访问。

https://81j44yaaab.execute-api.us-east-1.amazonaws.com/ipe/media/screen%20shot%202022-02-02%20at%202.00.29%20pm.png

但是,这个存储库也是一个页面站点,可以很好地提供图像。

https://rollthecloudinc.github.io/ipe-objects/media/screen%20shot%202022-02-02%20at%202.00.29%20pm.png

谢谢

进一步调试,日志中的 text 属性似乎为空。

isbinary 属性值为 false 会导致发现拼写错误。图形 ql 调用的名称输入缺少 -objects。纠正拼写错误后,isbinary 开始显示为 true。但是,text 属性值仍然为空。

已经设法找到一些类似的问题,但对于上传,许多人建议图 ql 并不是上传二进制数据的正确工具。因此,我们决定尝试使用 github rest v3 api,而不是追尾。具体来说,是 golang 的 go-github 包。

https://github.com/google/go-github

也许改用 rest api 会获得成功的结果。


正确答案


需要执行额外的步骤来获取通过 graph ql api 查询的对象的 blob 内容。一旦实现这一点,媒体文件就成功提供了。这需要使用 go-github blob api 从 github 获取 blob base64 内容。

https://81j44yaaab.execute-api.us-east-1.amazonaws.com/ipe/media/Screen%20Shot%202022-02-02%20at%202.00.29%20PM.png

getmediafile lambda

func GetMediaFile(req *events.APIGatewayProxyRequest, ac *ActionContext) (events.APIGatewayProxyResponse, error) {
    res := events.APIGatewayProxyResponse{StatusCode: 500}

    pathPieces := strings.Split(req.Path, "/")
    siteName := pathPieces[1]
    file, _ := url.QueryUnescape(pathPieces[3]) // pathPieces[2]

    log.Print("requested media site: " + siteName)
    log.Print("requested media file: " + file)

    // buf := aws.NewWriteAtBuffer([]byte{})

    // downloader := s3manager.NewDownloader(ac.Session)

    /*_, err := downloader.Download(buf, &s3.GetObjectInput{
        Bucket: aws.String(ac.BucketName),
        Key:    aws.String("media/" + file),
    })

    if err != nil {
        return res, err
    }*/

    ext := strings.Split(pathPieces[len(pathPieces)-1], ".")
    contentType := mime.TypeByExtension(ext[len(ext)-1])

    if ext[len(ext)-1] == "md" {
        contentType = "text/markdown"
    }

    suffix := ""
    if os.Getenv("GITHUB_BRANCH") == "master" {
        suffix = "-prod"
    }

    owner := "rollthecloudinc"
    repo := siteName + "-objects" + suffix

    var q struct {
        Repository struct {
            Object struct {
                ObjectFragment struct {
                    Oid githubv4.GitObjectID
                } `graphql:"... on Blob"`
            } `graphql:"object(expression: $exp)"`
        } `graphql:"repository(owner: $owner, name: $name)"`
    }
    qVars := map[string]interface{}{
        "exp":   githubv4.String(os.Getenv("GITHUB_BRANCH") + ":media/" + file),
        "owner": githubv4.String(owner),
        "name":  githubv4.String(repo),
    }

    err := ac.GithubV4Client.Query(context.Background(), &q, qVars)
    if err != nil {
        log.Print("Github latest file failure.")
        log.Panic(err)
    }

    oid := q.Repository.Object.ObjectFragment.Oid
    log.Print("Github file object id " + oid)

    blob, _, err := ac.GithubRestClient.Git.GetBlob(context.Background(), owner, repo, string(oid))
    if err != nil {
        log.Print("Github get blob failure.")
        log.Panic(err)
    }

    res.StatusCode = 200
    res.Headers = map[string]string{
        "Content-Type": contentType,
    }
    res.Body = blob.GetContent()
    res.IsBase64Encoded = true
    return res, nil
}

完整来源:https://github.com/rollthecloudinc/verti-go/blob/master/api/media/main.go

今天关于《从 Github Graph QL API 下载图像文件以使用 Golang》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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