使用 Iris-go 处理 body post
Handle body post using Iris-go
我是 Golang 的新手,我一直在做一些代码测试以使用 Iris 框架构建 REST API,我正在尝试从 Post 到我的 API 但我无法让它工作,我确实阅读了 Body 活页夹 http://iris-go.com/body_binder/ 并按照示例进行操作。我得到的结果是一个空结构:
我的代码:
package main
import (
"github.com/kataras/iris"
"fmt"
)
type PostAPI struct {
*iris.Context
}
type Lead struct {
fbId string
email string
telefono string
version string
mac string
os string
}
func (p PostAPI) Post(){
lead := Lead{}
err := p.ReadJSON(&lead)
if (err != nil) {
fmt.Println("Error on reading form: " + err.Error())
return
}
fmt.Printf("Post! %v", lead)
}
func main() {
iris.API("/", PostAPI{})
iris.Listen(":8080")
}
post:
curl -H "Content-Type: application/json" -X POST -d '{"fbId": "werwer","email": "werwer@gmail.com","telefono": "5555555555","version": "123","mac": "3j:3j:3j:3j","os": "uno bien chido"}' http://0.0.0.0:8080/
结果:
Post! { }
我做错了什么?
您应该尝试导出结构中带有 json 标签的字段
即
type Lead struct {
FbId string `json:"fbId"`
Email string `json:"email"`
Telefono string `json:"telefono"`
Version string `json:"version"`
Mac string `json:"mac"`
Os string `json:"os"`
}
我是 Golang 的新手,我一直在做一些代码测试以使用 Iris 框架构建 REST API,我正在尝试从 Post 到我的 API 但我无法让它工作,我确实阅读了 Body 活页夹 http://iris-go.com/body_binder/ 并按照示例进行操作。我得到的结果是一个空结构:
我的代码:
package main
import (
"github.com/kataras/iris"
"fmt"
)
type PostAPI struct {
*iris.Context
}
type Lead struct {
fbId string
email string
telefono string
version string
mac string
os string
}
func (p PostAPI) Post(){
lead := Lead{}
err := p.ReadJSON(&lead)
if (err != nil) {
fmt.Println("Error on reading form: " + err.Error())
return
}
fmt.Printf("Post! %v", lead)
}
func main() {
iris.API("/", PostAPI{})
iris.Listen(":8080")
}
post:
curl -H "Content-Type: application/json" -X POST -d '{"fbId": "werwer","email": "werwer@gmail.com","telefono": "5555555555","version": "123","mac": "3j:3j:3j:3j","os": "uno bien chido"}' http://0.0.0.0:8080/
结果:
Post! { }
我做错了什么?
您应该尝试导出结构中带有 json 标签的字段 即
type Lead struct {
FbId string `json:"fbId"`
Email string `json:"email"`
Telefono string `json:"telefono"`
Version string `json:"version"`
Mac string `json:"mac"`
Os string `json:"os"`
}