问题描述
我试图通过达到与Echo一起提供的POST请求来对pokemon API进行简单的API调用。
我正在使用主体{ "pokemon": "pikachu" }
向localhost:8000 / pokemon发送一个POST请求,其中身体通过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"`
}