无法将 POST 正文绑定到 Go 中的 URL
时间:2024-04-17
浏览:238
作者:佚名
Golang不知道大家是否熟悉?今天我将给大家介绍《无法将 POST 正文绑定到 Go 中的 URL》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!
问题内容
我正在尝试通过到达我使用 echo 提供的 post 请求来对 pokemon api 进行简单的 api 调用。
我正在向“localhost:8000/pokemon”发送一个 post 请求,主体为 { "pokemon": "pikachu" },其中主体通过 ioutil 重新附加到请求,更改使用正文:“localhost:8000/pokemon/pikachu”。
post 请求通过响应一些 json 来工作,但所进行的调用仅针对“localhost:8000/pokemon”,并且似乎正文未添加到 url 中。
我认为这里的绑定有问题 u := new(pokemon)
大家有什么想法吗?
func main() {
e := echo.new() // middleware
e.use(middleware.logger()) // logger
e.use(middleware.recover())
//cors
e.use(middleware.corswithconfig(middleware.corsconfig{
alloworigins: []string{"*"},
allowmethods: []string{echo.get, echo.head, echo.put, echo.patch, echo.post, echo.delete},
}))
// root route => handler
e.get("/", func(c echo.context) error {
return c.string(http.statusok, "hello, world!\n")
})
e.post("/pokemon", controllers.grabprice) // price endpoint
// server
e.logger.fatal(e.start(":8000"))
}
type pokemon struct { pokemon string `json:"pokemon" form:"pokemon" query:"pokemon"`
}
// GrabPrice - handler method for binding JSON body and scraping for stock price
func GrabPrice(c echo.Context) (err error) {
// Read the Body content
var bodyBytes []byte
if c.Request().Body != nil {
bodyBytes, _ = ioutil.ReadAll(c.Request().Body)
}
// Restore the io.ReadCloser to its original state
c.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
u := new(pokemon)
er := c.Bind(u) // bind the structure with the context body
// on no panic!
if er != nil {
panic(er)
}
// company ticker
ticker := u.pokemon
print("Here", string(u.pokemon))
// yahoo finance base URL
baseURL := "https://pokeapi.co/api/v2/pokemon"
print(baseURL + ticker)
// price XPath
//pricePath := "//*[@name=\"static\"]"
// load HTML document by binding base url and passed in ticker
doc, err := htmlquery.LoadURL(baseURL + ticker)
// uh oh :( freak out!!
if err != nil {
panic(err)
}
// HTML Node
// from the Node get inner text
price := string(htmlquery.InnerText(doc))
return c.JSON(http.StatusOK, price)
}解决方案
添加@mkopriva和@a.lorefice已经回答的内容
是的,您需要确保导出变量,以便绑定正常工作。 由于底层绑定过程实际上使用了结构上的反射机制。请参阅 this 文档,滚动到结构部分以查看它是什么。
type pokemon struct {
Pokemon string `json:"pokemon" form:"pokemon" query:"pokemon"`
}今天关于《无法将 POST 正文绑定到 Go 中的 URL》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
