【问题标题】:Using JSON requests in Google App Engine (Go programming language)在 Google App Engine(Go 编程语言)中使用 JSON 请求
【发布时间】:2023-03-23 02:50:01
【问题描述】:

我正在尝试使用 Go 将 JSON 格式的请求从我的应用程序的 Javascript 前端发送到 App Engine。如何将请求解析为处理程序中的结构?

比如说我的请求是一个带有请求负载的 POST

{'Param1':'Value1'}

我的结构是

type Message struct {
    Param1 string
  }                                    

和变量

var m Message                               

应用引擎文档中的示例使用 FormValue 函数来获取标准请求值,而当您使用 json 时,这似乎不起作用。

一个简单的例子将不胜感激。

【问题讨论】:

    标签: json google-app-engine go


    【解决方案1】:

    官方文档还不错,见:

    http://golang.org/doc/articles/json_and_go.html

    它提供了编码/解码为已知结构的示例(您的示例),还展示了如何使用反射来实现,类似于您通常在更多脚本语言中的实现方式。

    【讨论】:

    • 我遇到的问题是我不知道将请求的哪一部分(类型 *http.Request)传递给解码函数(需要 io.Reader 作为输入)。
    • 对于 POST 请求,使用响应正文。这应该包含“原始” JSON 数据(只是一个 JSON 编码的数据结构,它是一个简单的字符串)。
    • 这实际上取决于服务器,它如何发回 JSON 数据。通常使用响应正文来完成。
    • 如果您需要发送 JSON(您可能正在尝试,基于我重读您的问题),您需要将其编码为字符串,并将其作为 POST(命名)字段发送。但它必须与服务器期望找到它的位置相同。
    【解决方案2】:

    您可以在表单字段中发送数据,但通常您只会从response.Body 中读取数据。这是一个最小的 jQuery 和 App Engine 示例:

    package app
    
    import (
        "encoding/json"
        "fmt"
        "io/ioutil"
        "net/http"
        "strings"
    )
    
    func init () {
        http.HandleFunc("/", home)
        http.HandleFunc("/target", target)
    }
    
    const homePage =
    `<!DOCTYPE html>
    <html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    </head>
    <body>
        <form action="/target" id="postToGoHandler">
        <input type="submit" value="Post" />
        </form>
        <div id="result"></div>
    <script>
    $("#postToGoHandler").submit(function(event) {
        event.preventDefault();
        $.post("/target", JSON.stringify({"Param1": "Value1"}),
            function(data) {
                $("#result").empty().append(data);
            }
        );
    });
    </script>
    </body>
    </html>`
    
    func home(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, homePage)
    }
    
    type Message struct {
        Param1 string
    }
    
    func target(w http.ResponseWriter, r *http.Request) {
        defer r.Body.Close()
        if body, err := ioutil.ReadAll(r.Body); err != nil {
            fmt.Fprintf(w, "Couldn't read request body: %s", err)
        } else {
            dec := json.NewDecoder(strings.NewReader(string(body)))
            var m Message
            if err := dec.Decode(&m); err != nil {
                fmt.Fprintf(w, "Couldn't decode JSON: %s", err)
            } else {
                fmt.Fprintf(w, "Value of Param1 is: %s", m.Param1)
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-28
      • 2011-07-02
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多