【问题标题】:GO SDK for Google Translation api is returning HTML instead of JSON responseGO SDK for Google Translation api 返回 HTML 而不是 JSON 响应
【发布时间】:2021-12-01 00:29:16
【问题描述】:

我正在使用以下代码进行翻译:


import (
    "context"

    "cloud.google.com/go/translate"
    "golang.org/x/text/language"
    "google.golang.org/api/option"
)

func TranslateFromGoogle(sourceArr []string, srcLangCode, trgtLangCode, apiKey string) (targetArr []translate.Translation, err error) {
    src, err := language.Parse(srcLangCode)
    if err != nil {
        return targetArr, err
    }
    trgt, err := language.Parse(trgtLangCode)
    if err != nil {
        return targetArr, err
    }
    ctx := context.Background()
    opts := option.WithAPIKey(apiKey)
    c, err := translate.NewClient(ctx, opts)
    if err != nil {
        return targetArr, err
    }
    defer c.Close()
    targetArr, err = c.Translate(ctx, sourceArr, trgt,
        &translate.Options{
            Source: src,
            Format: translate.Text,
        })
    return targetArr, err
}

在错误中,返回以下类型的数据:

googleapi: got HTTP response code 400 with body: <!DOCTYPE html>\n<html lang=en>\n  <meta charset=utf-8>\n  <meta name=viewport content=\"initial-scale=1, minimum-scale=1, width=device-width\">\n  <title>Error 400 (Bad Request)!!1</title>\n  <style>\n    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}\n  </style>\n  <a href=//www.google.com/><span id=logo aria-label=Google></span></a>\n  <p><b>400.</b> <ins>That’s an error.</ins>\n  <p>Your client has issued a malformed or illegal request.  <ins>That’s all we know.</ins>\n

但我只想要这样的文本:

Your client has issued a malformed or illegal request.

是我遗漏了什么还是 SDK 问题?如何获得所需的消息作为输出?

【问题讨论】:

  • HTTP 状态码 400 的意思是“错误请求”——你为什么不去查一下呢?您可以将该 HTML 输出(以 &lt;!DOCTYPE html&gt;… 开头)保存到一个文件(以“.html”结尾)扩展名中,然后在任何浏览器中打开它——通过双击该文件——以实际阅读那里的内容。是什么阻止了你这样做?
  • @kostix 它以这种格式为每个状态代码返回错误,就像我收到的代码 412 一样。我在 api 中使用这个函数,所以当这个函数返回错误时,我需要从我的 api 返回消息。在我的情况下,在浏览器中打开 html 没有任何意义。
  • 状态码告诉你几乎所有你需要知道的事情。错误消息未提供任何其他详细信息。
  • 在这个场景中,如果我传递了大量要翻译的字符串但我的 api 密钥不支持那么多字符,那么它会作为错误请求返回。这是不合适的。它应该返回正确的消息。如果我直接调用 google api,那将返回问题的实际消息。我现在被困在这里了。
  • 您是否尝试使用 Translate strings 文档中记录的“响应 [0].text”?

标签: html go google-translation-api


【解决方案1】:

方法应该是解析错误输出并从中获取所需的消息。

package main

import (
    "fmt"
    "strings" 
    "bytes"
    
    "golang.org/x/net/html"
)

func main() {

    var s []string 
    
    string := "googleapi: got HTTP response code 400 with body: <!DOCTYPE html>\n<html lang=en>\n  <meta charset=utf-8>\n  <meta name=viewport content=\"initial-scale=1, minimum-scale=1, width=device-width\">\n  <title>Error 400 (Bad Request)!!1</title>\n  <style>\n    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}\n  </style>\n  <a href=//www.google.com/><span id=logo aria-label=Google></span></a>\n  <p><b>400.</b> <ins>That’s an error.</ins>\n  <p>Your client has issued a malformed or illegal request.  <ins>That’s all we know.</ins>\n"
    doc, err := html.Parse(strings.NewReader(string))
    if err != nil { 
        fmt.Println(err)
    }
    
    var f func(*html.Node)
    f = func(n *html.Node) {
        
        if n.Type == html.ElementNode && n.Data == "p" {
            text := &bytes.Buffer{}
            collectText(n, text)
            s = append(s, text.String())
        }
        for c := n.FirstChild; c != nil; c = c.NextSibling {
            f(c)
        }
    }
    f(doc)
    
    fmt.Println(s[1]) // return value
}

func collectText(n *html.Node, buf *bytes.Buffer) {
    if n.Type == html.TextNode {
        buf.WriteString(n.Data)
    }
    for c := n.FirstChild; c != nil; c = c.NextSibling {
        collectText(c, buf)
    }
}

输出:

Your client has issued a malformed or illegal request.  That’s all we know.

更新:要解释为什么应该使用上述方法,您必须检查“翻译”功能的工作原理:

func (c *Client) Translate(ctx context.Context, inputs []string, target language.Tag, opts *Options) ([]Translation, error)

所以,如你所见,它返回一个翻译类型和错误类型,分别是:

// translation
type Translation struct {
    Text string
    Source language.Tag
    Model string
} 

// error
type error interface {
    Error() string
}

查看更多here

总之,您必须解析错误字符串才能获得所需的输出。

【讨论】:

  • 你好@Amandeepkaur。你成功了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-27
  • 2018-12-19
  • 2021-10-19
  • 2017-03-28
  • 2019-03-31
  • 2020-08-12
  • 1970-01-01
相关资源
最近更新 更多