Make a PUT request in Go (with JSON body)

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

type MyRequest struct {
	Name  string `json:"name"`
	Color string `json:"color"`
	Size  int    `json:"size"`
}

type MyResponse struct {
	Status string `json:"status"`
}

func doRequest(httpMethod string, address string, requestBody MyRequest, responseBody *MyResponse) (err error) {
	j, err := json.Marshal(requestBody)
	if err != nil {
		return
	}
	req, err := http.NewRequest(httpMethod, address, bytes.NewReader(j))
	if err != nil {
		return
	}
	req.Header.Set("Content-type", "application/json")
	client := http.Client{Timeout: time.Second * 10}
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	if resp.StatusCode >= 400 {
		return fmt.Errorf("Request failed with status %d", resp.StatusCode)
	}
	err = json.NewDecoder(resp.Body).Decode(responseBody)
	if err != nil {
		return
	}
	return
}

func main() {
	responseBody := new(MyResponse)
	err := doRequest("PUT", "https://example.com/endpoint", MyRequest{Name: "bakert", Color: "red", Size: 10}, responseBody)
	if err != nil {
		fmt.Println("Failed", err)
	} else {
		fmt.Println("Status", responseBody.Status)
	}
}

Leave a Reply

Your email address will not be published.