go - 无法将 POST 正文绑定(bind)到 Go 中的 URL

标签 go post bind

我正在尝试通过达到我与 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/

相关文章:

python - 访问绑定(bind)到事件的函数的返回值 (tkinter)

javascript - 获取已选中和未选中的复选框值

go - 在项目中导入pb.go文件

go - 一些如何在 go 程序使用中显示各种测试参数标志

php - 简单的mailto集成查询

jquery - 防止隐形表单被轻易黑客入侵

c++ - std::bind 占位符的重载运算符

optimization - 约束单目标优化

datetime - 在 Go 中,给定一个位置名称,我们如何确定该位置的当前时间?

javascript - 使用 Python 请求库发布到 .jsp 网站