我是 Go 的新手,所以如果这很愚蠢,请原谅我。
我正在尝试使用 gorest 将表单发布到用 Go 编写的 REST API。我已经使用 GET 成功完成了此操作,但无法将 POST 数据解析为 map 。这是我的 Go 代码
gotest.go:
package main
import (
"code.google.com/p/gorest"
"net/http"
"fmt"
)
func main() {
gorest.RegisterService(new(HelloService)) //Register our service
http.Handle("/",gorest.Handle())
http.ListenAndServe(":8787",nil)
}
//Service Definition
type HelloService struct {
gorest.RestService `root:"/api/"`
save gorest.EndPoint `method:"POST" path:"/save/" output:"string" postdata:"map[string]string"`
}
func(serv HelloService) Save(PostData map[string]string) {
fmt.Println(PostData)
}
还有我很棒的 html 表单:
<form method="POST" action="http://127.0.0.1:8787/api/save/">
key: <input type="text" name="key" /><br />
json: <input type="text" name="json" /><br />
<input type="submit" />
</form>
我认为这会将我的帖子数据变成我可以访问的漂亮 map 。我填写了表格,点击提交,它返回了一个错误:
使用 application/json 解码数据时出错。客户端在实体中发送了不兼容的数据格式。 (寻找值开头的无效字符“k”)
编辑:正如 greggory.hz 指出的那样,该程序似乎认为发布数据是一个 json。此错误是因为 json 必须以大括号、方括号或引号开头。
如果 map[string]string
带有 string
,它会在我运行它的 bash 终端上打印以下内容:
key=arst&json=%7B%27arst%27%3A%27arst%27%7D
在 go rest 文档中,我能找到的唯一示例是:
posted gorest.EndPoint method:"POST" path:"/post/" postdata:"User"
func(serv HelloService) Posted(posted User)
但是我创建自定义结构的尝试也失败了,出现了上面看到的相同的解码错误。
type MyStruct struct {
key,json string
}
有人可以告诉我应该使用什么数据类型吗?
最佳答案
您正在尝试将 html 表单发布到需要 json 正文的服务。但是您的浏览器不会将帖子格式化为 application/json。它会将其格式化为 urlencoded 正文。问题不在您的 go 服务器代码中,而是在 html 表单中。您可能想使用 javascript 来打包和发送您的帖子,而不是标准的 html 表单。
<div>
<input type="hidden" name="endpont" value="http://127.0.0.1:8787/api/save/" />
key: <input type="text" name="key" /><br /> <!-- this should be used in your post url -->
json: <input type="text" name="json" /><br /> <!-- this will get sent by your javascript as the post body -->
<input type="button" onclick="send_using_ajax();" />
</div>
关于go - 我应该在森林的 POST 请求中使用什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16801468/