在Google App Engine中使用JSON请求(Go编程语言)

huangapple go评论82阅读模式
英文:

Using JSON requests in Google App Engine (Go programming language)

问题

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

举个例子,假设我的请求是一个带有请求有效负载的POST请求:

{'Param1':'Value1'}

而我的结构体是:

type Message struct {
    Param1 string
}

以及变量:

var m Message

在App Engine文档中的示例中,使用FormValue函数来获取标准请求值,但是当你使用JSON时,这种方法似乎不起作用。

非常感谢提供一个简单的示例。

英文:

I am trying to send requests in JSON format from the Javascript front-end of my application to App Engine using Go. How do I parse the request to a struct in the handler?

Say for example my request is a POST with the request payload

{'Param1':'Value1'}

and my struct is

type Message struct {
    Param1 string
  }                                    

and the variable

var m Message                               

The examples in the app engine documentation use the FormValue function for getting standard request values, and this doesn't seem to work when you use json.

A simple example would be greatly appreciated.

答案1

得分: 5

官方文档非常好,可以参考:

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

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

英文:

The official documentation is pretty good, see:

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

It has examples both for encoding/decoding to a known structure (your example), but also shows how to do it using reflection, similar to how you would typically do it in more scripty languages.

答案2

得分: 1

你可以将数据发送到一个表单字段中,但通常你只需要从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)
        }
    }
}
英文:

You could send the data in a form field, but typically you'll just read it from the response.Body. Here's a minimal jQuery & App Engine example:

package app

import (
    &quot;encoding/json&quot;
    &quot;fmt&quot;
    &quot;io/ioutil&quot;
    &quot;net/http&quot;
    &quot;strings&quot;
)

func init () {
    http.HandleFunc(&quot;/&quot;, home)
    http.HandleFunc(&quot;/target&quot;, target)
}

const homePage =
`&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;script src=&quot;//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form action=&quot;/target&quot; id=&quot;postToGoHandler&quot;&gt;
    &lt;input type=&quot;submit&quot; value=&quot;Post&quot; /&gt;
    &lt;/form&gt;
    &lt;div id=&quot;result&quot;&gt;&lt;/div&gt;
&lt;script&gt;
$(&quot;#postToGoHandler&quot;).submit(function(event) {
    event.preventDefault();
    $.post(&quot;/target&quot;, JSON.stringify({&quot;Param1&quot;: &quot;Value1&quot;}),
        function(data) {
            $(&quot;#result&quot;).empty().append(data);
        }
    );
});
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;`

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, &quot;Couldn&#39;t read request body: %s&quot;, err)
    } else {
        dec := json.NewDecoder(strings.NewReader(string(body)))
        var m Message
        if err := dec.Decode(&amp;m); err != nil {
            fmt.Fprintf(w, &quot;Couldn&#39;t decode JSON: %s&quot;, err)
        } else {
            fmt.Fprintf(w, &quot;Value of Param1 is: %s&quot;, m.Param1)
        }
    }
}

huangapple
  • 本文由 发表于 2013年1月20日 04:34:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/14418581.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定