英文:
How to make HTTP Patch request to raven db server using golang?
问题
我已经编写了以下代码,将标题字段添加到我的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>
</html>
请问有人可以指出我在上述代码中漏掉了什么吗?
英文:
I have written the following code to add a title field to the document 1 in my raven database.
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))
I don't understand why it is not working? I am getting the following response Body which is not what I am expecting. I am expecting a success response.
<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>
</html>
Can someone please point out what am I missing in the above code?
答案1
得分: 7
对于 PATCH 请求,您需要传递一个包含要执行的补丁命令的数组(以 JSON 格式)。
要更改 title
属性,代码如下:
var jsonStr = []byte(`[{"Type": "Set", "Name": "title", "Value": "买奶酪和面包作为早餐。"}]`)
英文:
For PATCH request, you need to pass an array with patch commands (in json format) to execute.
To change the title
attribute, it will look like:
var jsonStr = []byte(`[{"Type": "Set", "Name": "title", "Value": "Buy cheese and bread for breakfast."}]`)
答案2
得分: 3
PATCH
和POST
是不同的HTTP动词。
我认为你只需要将这段代码中的:
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
改为:
req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jsonStr))
或者至少这是第一步。根据评论,我猜测你的请求体也有问题。
英文:
PATCH
and POST
are different http verbs.
I think you just need to change this;
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
to
req, _ := http.NewRequest("PATCH", url, bytes.NewBuffer(jsonStr))
Or at least that is the first thing. Based on comments I would speculate the body of your request is also bad.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论