【问题标题】:How to make HTTP Patch request to raven db server using golang?如何使用 golang 向 raven db 服务器发出 HTTP Patch 请求?
【发布时间】:2015-08-27 17:14:29
【问题描述】:

我编写了以下代码,为我的 raven 数据库中的文档 1 添加一个标题字段。

url := "http://localhost:8083/databases/drone/docs/1"
fmt.Println("URL:>", url)

var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)
req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jsonStr))
req.Header.Set("X-Custom-Header", "myvalue")
req.Header.Set("Content-Type", "application/json")

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
    panic(err)
}
defer resp.Body.Close()

body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))

我不明白为什么它不起作用?我收到以下响应正文,这不是我所期望的。我期待一个成功的回应。

<html>
<body>
    <h1>Could not figure out what to do</h1>
    <p>Your request didn't match anything that Raven knows to do, sorry...</p>
</body>

谁能指出我在上面的代码中遗漏了什么?

【问题讨论】:

  • 我认为curl -X POST -d '{"title": "Buy cheese and bread for breakfast."}' -H 'X-Custom-Header: myvalue' -H 'Content-Type: application/json' http://localhost:8083/databases/drone/docs/1 可以工作吗?
  • 如果你想要一个 PATCH 请求,你为什么要做一个 POST?
  • 哈,不错@JimB(没注意标题)
  • 对不起@JimB 我正在尝试使用 post、get 等。对于所有这些请求,我都遇到了同样的错误。我将编辑代码:)

标签: go ravendb ravendb-http


【解决方案1】:

对于PATCH请求,需要传递一个带有补丁命令的数组(json格式)来执行。

要更改title 属性,它将如下所示:

var jsonStr = []byte(`[{"Type": "Set", "Name": "title", "Value": "Buy cheese and bread for breakfast."}]`)

【讨论】:

    【解决方案2】:

    PATCH 和 POST 是不同的 http 动词。

    我认为你只需要改变这个;

     req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    

    到

     req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jsonStr))
    

    或者至少这是第一件事。根据 cmets,我推测您的请求正文也很糟糕。

    【讨论】:

    • 将此代码与 Rails 服务器一起使用,我需要包含 req.Header.Set("Content-Type", "application/json")
    • @RickSmith 是的,内容类型标头将经常需要。如果 HTTP 请求由于未知原因而失败,检查您的标头总是值得的。
    猜你喜欢
    • 2020-10-08
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多