如何使用golang向raven db服务器发出HTTP Patch请求?

6
我已经编写了以下代码,将标题字段添加到我的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 可以正常工作,是吗? - sberry
1
如果你想要一个PATCH请求,为什么要发一个POST请求呢? - JimB
哈,@JimB 发现得好(我没有足够注意标题)。 - sberry
抱歉@JimB,我尝试使用post、get等方法,但所有这些请求都出现了相同的错误。我会编辑代码 :) - Prashant
2个回答

7
对于 PATCH 请求,您需要传递一个包含要执行的修补程序命令的数组(以 json 格式)。
要更改 title 属性,看起来应该是这样的:
var jsonStr = []byte(`[{"Type": "Set", "Name": "title", "Value": "Buy cheese and bread for breakfast."}]`)

3
PATCHPOST是不同的HTTP动词。
我认为你只需要修改这个;
 req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))

为了

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

至少这是第一件事。根据评论,我猜测您的请求正文也很糟糕。

3
在使用Rails服务器时,我需要包含req.Header.Set("Content-Type", "application/json")这段代码。 - Rick Smith
@RickSmith 是的,content-type头部通常是必需的。如果HTTP请求因未知原因失败,检查您的头部总是值得的。 - evanmcdonnal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接