我正在尝试通过达到我与 Echo 一起服务的 POST 请求来对 pokemon API 进行简单的 API 调用。
我正在向“localhost:8000/pokemon”发送一个带有正文 { "pokemon": "pikachu" }
的 POST 请求其中 BODY 通过 ioutil 更改要使用主体发出的请求重新附加到请求:“localhost:8000/pokemon/pikachu”。
POST 请求通过响应一些 JSON 来工作,但所进行的调用仅针对“localhost:8000/pokemon”,并且似乎正文未添加到 URL。
我认为这里的绑定(bind)有问题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 已经回答的内容
是的,您需要确保已导出变量,以便绑定(bind)正常工作。
由于底层绑定(bind)的过程实际上在结构上使用了反射机制。见 this文档,滚动到 Structs 部分以查看它是什么。
type pokemon struct {
Pokemon string `json:"pokemon" form:"pokemon" query:"pokemon"`
}
关于go - 无法将 POST 正文绑定(bind)到 Go 中的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63504015/