在Google App Engine(Go编程语言)中使用JSON请求
我正在尝试使用Go将JSON格式的请求从应用程序的Javascript前端发送到应用程序引擎。如何将请求解析为处理程序中的结构 例如,假设我的请求是带有请求负载的POST在Google App Engine(Go编程语言)中使用JSON请求,json,google-app-engine,go,Json,Google App Engine,Go,我正在尝试使用Go将JSON格式的请求从应用程序的Javascript前端发送到应用程序引擎。如何将请求解析为处理程序中的结构 例如,假设我的请求是带有请求负载的POST {'Param1':'Value1'} 我的结构是 type Message struct { Param1 string } 变量呢 var m Message appeng
{'Param1':'Value1'}
我的结构是
type Message struct {
Param1 string
}
变量呢
var m Message
appengine文档中的示例使用FormValue函数获取标准请求值,而这在使用json时似乎不起作用
请举一个简单的例子。官方文档非常好,请参见:
它既有用于编码/解码到已知结构(您的示例)的示例,也展示了如何使用反射进行编码/解码,类似于您通常使用更多脚本语言进行编码的方式。您可以在表单字段中发送数据,但通常只从
响应.Body
读取数据。下面是一个简单的jQuery和应用程序引擎示例:
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)
}
}
}
package应用程序
进口(
“编码/json”
“fmt”
“io/ioutil”
“net/http”
“字符串”
)
func init(){
http.HandleFunc(“/”,home)
http.HandleFunc(“/target”,target)
}
康斯特网页=
`
$(“#PostHandler”).submit(函数(事件){
event.preventDefault();
$.post(“/target”,JSON.stringify({“Param1”:“Value1”}),
功能(数据){
$(“#结果”).empty().append(数据);
}
);
});
`
func home(w http.ResponseWriter,r*http.Request){
fmt.Fprint(w,主页)
}
类型消息结构{
参数1字符串
}
func目标(w http.ResponseWriter,r*http.Request){
延迟r.Body.Close()
if body,err:=ioutil.ReadAll(r.body);err!=nil{
fmt.Fprintf(w,“无法读取请求正文:%s”,错误)
}否则{
dec:=json.NewDecoder(strings.NewReader(string(body)))
var m消息
如果错误:=dec.Decode(&m);错误!=nil{
Fprintf(w,“无法解码JSON:%s”,错误)
}否则{
fmt.Fprintf(w,“参数1的值为:%s”,m.Param1)
}
}
}
我的问题是,我不知道请求的哪一部分(键入*http.request)要传递给解码函数(需要io.Reader作为输入)。对于POST请求,请使用响应正文。它应该包含“原始”JSON数据(简单地说是一个JSON编码的数据结构,它是一个简单的字符串)。它实际上取决于服务器,它如何发回JSON数据。通常使用响应体完成。如果需要发送JSON(根据我重读您的问题,您可能正在尝试发送JSON),则需要将其编码为字符串,并将其作为POST(命名)字段发送。但它必须位于服务器期望找到它的同一命名字段中。