6

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>

Can someone please point out what am I missing in the above code?

Prashant
  • 3,823
  • 3
  • 25
  • 40
  • I assume `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` works then? – sberry Aug 27 '15 at 17:18
  • 1
    If you want a PATCH request, why are you making a POST? – JimB Aug 27 '15 at 17:20
  • Ha, good catch @JimB (didn't pay enough attention to the title) – sberry Aug 27 '15 at 17:21
  • Sorry @JimB I was trying with post, get etc. I am getting same error for all these requests. I will edit the code :) – Prashant Aug 27 '15 at 17:22

2 Answers2

7

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."}]`)
dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85
3

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.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • 3
    Using this code with a rails server I needed to include `req.Header.Set("Content-Type", "application/json")` – Rick Smith Jun 14 '16 at 19:39
  • @RickSmith yeah the content-type header is going to be required more often than not. Checking your header is always worth while if an HTTP request is failing for unkown reasons. – evanmcdonnal Jun 14 '16 at 21:30