Essential Go HTTP Client  Suggest an edit

PUT request of JSON object

http.Client doesn’t have a convenience method for doing PUT requests, so we construct a http.Request object and use http.Client.Do(req *http.Request) to perform that request.

user := User{
	Name:  "John Doe",
	Email: "johndoe@example.com",
}

d, err := json.Marshal(user)
if err != nil {
	log.Fatalf("json.Marshal() failed with '%s'\n", err)
}

client := &http.Client{}
client.Timeout = time.Second * 15

uri := "https://httpbin.org/put"
body := bytes.NewBuffer(d)
req, err := http.NewRequest(http.MethodPut, uri, body)
if err != nil {
	log.Fatalf("http.NewRequest() failed with '%s'\n", err)
}

req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := client.Do(req)
if err != nil {
	log.Fatalf("client.Do() failed with '%s'\n", err)
}

defer resp.Body.Close()
d, err = ioutil.ReadAll(resp.Body)
if err != nil {
	log.Fatalf("ioutil.ReadAll() failed with '%s'\n", err)
}

fmt.Printf("Response status code: %d, text:\n%s\n", resp.StatusCode, string(d))
Response status code: 200, text:
{
  "args": {}, 
  "data": "{\"Name\":\"John Doe\",\"Email\":\"johndoe@example.com\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept-Encoding": "gzip", 
    "Connection": "close", 
    "Content-Length": "49", 
    "Content-Type": "application/json; charset=utf-8", 
    "Host": "httpbin.org", 
    "User-Agent": "Go-http-client/1.1"
  }, 
  "json": {
    "Email": "johndoe@example.com", 
    "Name": "John Doe"
  }, 
  "origin": "24.5.174.236", 
  "url": "https://httpbin.org/put"
}

  ↑ ↓ to navigate     ↵ to select     Esc to close